<?php
/**
 * Created by PhpStorm.
 * User: Raytine
 * Date: 2021/11/18
 * Time: 10:01
 */

 namespace app\api\controller\deliver\v1;


use app\api\model\Capital;
use app\api\model\CapitalValue;
use app\api\model\Detailed;
use app\api\model\DetailedCategory;
use app\api\model\DetailedOption;
use app\api\model\DetailedOptionValue;
use app\api\model\DetailedWorkProcess;
use app\api\model\EnvelopeRecords;
use app\api\model\Envelopes;
use app\api\model\OrderModel;
use app\api\model\ProductsSpec;
use app\api\model\VisaForm;
use redis\RedisPackage;
use think\Controller;
use app\api\model\Authority;
use app\api\model\Common;
use think\Request;
use think\Exception;
use app\index\model\Pdf;
use  app\api\model\Approval;
use Think\Db;
use WeCom\WeCom;

class NewInfrastructure extends Controller {
    protected $us;
    protected $pdf;
    
    public function _initialize() {
        $this->us  = Authority::check(1);
        $this->pdf = new Pdf();
        
    }
    
    /*
     * 获取配置清单
     */
    public function newDetailedList(DetailedCategory $detailedCategory) {
        $data         = Authority::param(['type', 'group','orderId']);
        // $group        = $data['group'];
        $group        = 1;
        $pro_id=db('order')->where('order_id',$data['orderId'])->value('business_type');
       if($pro_id==2){
            $group        = 4;
        }
        if($pro_id==3){
            $group        = 5;
        }
        $detailedList = $detailedCategory->where('detailed_category.is_enable', 1);
        if ($data['type'] == 0) {
            $detailedList->where('is_agency', 0)->where('pid', 0)->with(['detailedList' => function ($query) use ($group) {
                $query->where('detailed.groupss', $group)->with('detailedListValue');
            }]);
        } else {
            $detailedList->where('is_agency', 1)->where('id', '<>', 22)->with(['detailedListAnge','detailedListAnge.detailedListValue']);
        }
        $detailedLists = $detailedList->order('detailed_category.sort desc')->select();
        if ($data['type'] == 0) {
            foreach ($detailedLists as $k => $ite) {
                if (!empty($ite['detailed_list'])) {
                    foreach ($ite['detailed_list'] as $l => $value) {
                        $value['title']      = $ite['title'];
                        $value['isWarranty'] = 1;
                        if (!empty($value['warrantYears']) && $value['warrantYears'] != '0.00') {
                            $value['warranty'] = ['warrantYears' => $value['warrantYears'], 'warrantyText1' => $value['warrantyText1'], 'exoneration' => $value['exoneration'],];
                        } else {
                            $value['warranty']   = null;
                            $value['isWarranty'] = 0;
                        }
                       
                        $value['types']    = 4;
                        $value['group']    = $value['groupss'];
                        $detailedListValue = $value->detailed_list_value;
                        $desc_attachment =array_column($detailedListValue, 'desc_attachment');
                        $non_empty_array = array_filter($desc_attachment, function($value) {
                            return !is_null($value) && $value !== '';
                        });
                        $value['desc_attachment']  =!empty($non_empty_array)?1:0;
                        if (!empty(array_column($detailedListValue, 'option_value_title'))) {
                            $value['detailedListValues'] = $value['detailed_title'] . ',' . implode(array_column($detailedListValue, 'option_value_title'), ',');
                            
                        } else {
                            $value['detailedListValues'] = $value['detailed_title'];
                        }
                        unset($value->detailedListValue,$value->detailed_list_value, $value['warrantYears'], $value['warrantyText1'], $value['exoneration'], $value['groupss']);
                    }
                    
                }
                
                if ($ite['id'] == 0) {
                    $detailedLists[$k]['detailed_list'] = isset($detailedListList) ? $detailedListList : [];
                }
                
                unset($detailedLists[$k]['sort'], $detailedLists[$k]['is_enable'], $detailedLists[$k]['created_at'], $detailedLists[$k]['updated_at'], $detailedLists[$k]['type'], $detailedLists[$k]['is_agency'], $detailedLists[$k]['condition']);
            }
        } else {
            $pidList = [];
            foreach ($detailedLists as $k => $l) {
                $l['type']=1;
                if ($l['pid'] != 0) {
                    $pidList[] = $l;
                }
               
            }
            $zi = [];
            foreach ($detailedLists as $k => $o) {
                $dataList = [];
                foreach ($pidList as $m => $l) {
                    if ($o['id'] == $l['pid']) {
                        $l['detailed_title']     = $l['title'];
                        $l['detailedListValues'] = '';
                        $l['types']              = 4;
                        $detailed_list_ange      = $l['detailed_list_ange'];
                        unset($pidList[$m]['detailed_list_ange']);
                        foreach ($detailed_list_ange as $b => $value) {
                           
                            $value['type']      =1;
                            $value['isWarranty'] = 1;
                            if (!empty($value['warrantYears']) && $value['warrantYears'] != '0.00') {
                                $value['warranty'] = ['warrantYears' => $value['warrantYears'], 'warrantyText1' => $value['warrantyText1'], 'exoneration' => $value['exoneration'],];
                            } else {
                                $value['warranty']   = null;
                                $value['isWarranty'] = 0;
                            }
                            $value['types']    = 4;
                            $value['group']    = $value['groupss'];
                            
                            $detailedListValue = $value->detailed_list_value;
                            $desc_attachment =array_column($detailedListValue, 'desc_attachment');
                            $non_empty_array = array_filter($desc_attachment, function($value) {
                                return !is_null($value) && $value !== '';
                            });
                            $value['desc_attachment']  =!empty($non_empty_array)?1:0;
                            if (!empty(array_column($detailedListValue, 'option_value_title'))) {
                                $value['detailedListValues'] = $value['detailed_title'] . ',' . implode(array_column($detailedListValue, 'option_value_title'), ',');
                                
                            } else {
                                $value['detailedListValues'] = $value['detailed_title'];
                            }
                            unset($value->detailedListValue,$value->detailed_list_value, $value['warrantYears'], $value['warrantyText1'], $value['exoneration'], $value['groupss']);
                            if ($value['userId'] != 0 && $value['userId']==$this->us['user_id']) {
                                $value['type']      =2;
                                $value['title']      =db('unit')->where('id', $value['un_id'])->value('title');
                                $value['specsList']    =  $value->detailedListValue;
                                $zi[] = $value;
                                unset($detailed_list_ange[$b]);
                            }else{
                                $value['square']      =0;
                                $value['title']      = $l['title'];
                            }
                        }
                        if (!empty($detailed_list_ange) &&  $l['title'] !="零采") {
                            $l['detailed_list_ange'] = array_merge($detailed_list_ange);
                            $dataList[]              = $l;
                        }
                    }
                }
                if (empty($dataList)) {
                    unset($detailedLists[$k]);
                } else {
                    $detailedLists[$k]['detailed_list'] = $dataList;
                }
            }
            $detailedLists = array_merge($detailedLists);
            $kl=[["id" => 20, "title" => "零采", "sort" => 10, "is_agency" => 1, "is_enable" => 1,'type'=>2, "created_at" => 1638168417, "updated_at" => null, "pid" => 0, "detailed_list" => [["id" => 135, "title" => "常用自定义清单(保存后才有)", "sort" => 4, "is_agency" => 1, "is_enable" => 1, "created_at" => null, "updated_at" => null, "pid" => 20,'type'=>2, "detailed_title" => "常用自定义清单(保存后才有)", "detailedListValues" => "", "types" => 4, "detailed_list_ange" => $zi]]]];
           
            $detailedLists=array_merge($detailedLists,$kl);
        }
        r_date($detailedLists, 200);
    }
    
    public function isGive() {
        $data            = Authority::param(['id', 'orderId']);
        $state           = db('order')->where('order_id', $data['orderId'])->value('state');
        $IsSmallOrderFee = [];
        if ($state > 3) {
            $IsSmallOrderFee = db('capital')->where('types', 1)->where('projectId', $data['id'])->where('enable', 1)->where(function ($quer) {
                $quer->where('products', 0)->whereOr(['products' => 1, 'unique_status' => 0, 'is_product_choose' => 1]);
            })->where('ordesr_id', $data['orderId'])->where('small_order_fee', '>', 0)->find();
        }
        $smallOrderFeeType = 0;
        if (!empty($IsSmallOrderFee)) {
            $smallOrderFeeType = 1;
        }
        $detailed = db('detailed')->where('detailed_id', $data['id'])->whereNull('deleted_at')->field('give')->find();
        r_date(['give' => $detailed['give'], 'smallOrderFeeType' => $smallOrderFeeType], 200);
    }
    
    /*
     * 获取报价配置选项
     */
     public function getDetailedOption(DetailedOption $detailedOption) {
        $data                   = Authority::param(['id']);
        $getOptionValue['list'] = $detailedOption->with(['detailedListOptionValues' => function ($query) use ($data) {
            $query->where('detailed_option_value.detailed_id', $data['id'])->group('detailed_option_value.option_value_id');
        }])->where('condition', '<>', 2)->order('option_id desc')->select();
        $detailed_option_sort   = db('detailed_option_sort', config('database.zong'))->where('detailed_id', $data['id'])->select();
        foreach ($getOptionValue['list'] as $k => $value) {
            if ($detailed_option_sort) {
                foreach ($detailed_option_sort as $item) {
                    if ($item['option_id'] == $value['option_id']) {
                        $value['sort'] = $item['sort'];
                    }
                    
                }
                
            }
            if (!empty($value['detailed_list_option_values'])) {
                $value['sort']           = isset($value['sort']) ? $value['sort'] : 0;
                foreach ($value['detailed_list_option_values'] as $key=>$val){
                    $val['desc_tag']           = empty($val['desc_tag']) ?null : json_decode($val['desc_tag'],true);
                    $title  = empty($val['desc_text']) ?null : json_decode($val['desc_text'],true);
                    //提点固定字
                    $val['settlementMethodPidTitle']='';
                    //点击进去进去介绍
                    $val['settlementMethodTitle']='';
                    $val['settlementMethodContent']='';
                    $val['directSales']=0;
                    if($val['settlement_method']==2 || $val['settlement_method']==3 || $val['settlement_method']==4){
                        $val['settlementMethodPidTitle']='固提';
                        $val['settlementMethodTitle']='';
                        if($val['settlement_method']==4 || $val['settlement_method']==3){
                            $val['settlementMethodTitle']='销售固定提点清单';
                            $val['directSales']=1;
                            $val['settlementMethodContent']='固定销售提成比例的清单，此规格固定提成为('.$val['fixed_rate'].'%)';
                        }
                        if($val['settlement_method']==2){
                            $val['settlementMethodTitle']='公司固定计提清单';
                            $val['settlementMethodContent']='与合同制公司计提比例不同，此规格为('.$val['fixed_rate'].'%)';
                        }
                    }
                    $val['desc_text'] ='';
                    $content=[];
                    if(!empty($title)){
                        foreach ($title as $v){
                            $content[]=$v['title'].':'.$v['value'].'。';
                        }
                        $val['desc_text']=implode($content,"<br/>");
                    }
                    $desc_attachment=empty($val['desc_attachment']) ?null: json_decode($val['desc_attachment'],true);
                    $val['desc_attachment']           ='';
                    if(!empty($desc_attachment)){
                        $val['desc_attachment']           =$desc_attachment[0];
                    }
                    
                }
              
                $getOptionList['list'][] = $value;
            }
        }
        $getOptionList['PushList'] = db('detailed')->join('detailed_relevance', 'detailed.detailed_id=detailed_relevance.relevance_detailed_id', 'left')->join('detailed_category', 'detailed.detailed_category_id=detailed_category.id', 'left')->field('detailed.detailed_title,detailed.detailed_id,detailed.agency,detailed.detailed_category_id,detailed.artificial,detailed_category.title')->where('detailed_relevance.detailed_id', $data['id'])->where('detailed.display', 1)->select();
        foreach ($getOptionList['PushList'] as $k => $item) {
            $getOptionList['PushList'][$k]['types'] = 4;
            
        }
        $getOptionList['PushList'] = empty($getOptionList['PushList']) ? [] : $getOptionList['PushList'];
        $Visa                      = new Visa();
        if (isset($getOptionList['list'])) {
            $getOptionList['list'] = $Visa->arraySort($getOptionList['list'], 'sort', SORT_ASC);
        }
        $detailed = db('detailed')->join('unit', 'unit.id=detailed.un_id')->where('detailed_id', $data['id'])->field('rmakes,unit.title,initial_volume_switch,initial_volume,small_order_fee,user_id,detailed.detailed_title as titles')->find();
        if ($detailed['initial_volume_switch'] == 2) {
            $detailed['initial_volume'] = 0;
        }
        $getOptionList['category']       = 1;
        if ($detailed['user_id']  != 0) {
            $getOptionList['category'] = 2;
        }
        $getOptionList['remarks']       = $detailed['rmakes'];
       
        $getOptionList['title']         = $detailed['title'];
        $getOptionList['detailedTitle']         = $detailed['titles'];
        $getOptionList['initialVolume'] = $detailed['initial_volume'];
        $small_order_fee                = null;
        if ($detailed['small_order_fee'] != '[]') {
            $small_order_fee = json_decode($detailed['small_order_fee'], true);
        }
        $getOptionList['smallOrderFee'] = $small_order_fee;
        r_date($getOptionList, 200);
    }
    
    /*
     * 报价模版
     */
    public function quotationTemplate() {
        $data       = Request::instance()->get();
        $template   = db('user_config', config('database.zong'))->where('key', 'quotation_template')->where('status', 1)->value('value');
        $sys_config = db('sys_config', config('database.zong'))->where('keyss', 'bureau_reform_' . config('city'))->where('statusss', 1)->value('valuess');
        $template   = json_decode($template, true);
        foreach ($template as $k => $value) {
            $template[$k]['group']     = 1;
            $template[$k]['mouldType'] = null;
        }
        
        if ($sys_config == 1) {
            array_push($template, ['id' => 14, 'title' => '点击此处，切换整装清水报价清单>  ', 'group' => 2, 'mouldType' => 2]);
        }
        if (isset($data['mouldType']) && $data['mouldType'] != 0) {
            foreach ($template as $k => $value) {
                if (!empty($value['mouldType'])) {
                    if ($data['mouldType'] == 1) {
                        $template[$k]['title']     = '点击此处，切换整装清水报价清单> ';
                        $template[$k]['mouldType'] = 2;
                    } else {
                        $template[$k]['title']     = '点击此处，切换局改维修报价清单> ';
                        $template[$k]['mouldType'] = 1;
                        
                    }
                    
                }
                $template[$k]['group'] = $data['mouldType'];
            }
        }
        r_date($template, 200);
    }
    
    /*
     * 报价模版
     */
    public function productOffer() {
        
        $data                = Authority::param(['order_id']);
        $envelopes           = db('envelopes')->where('ordesr_id', $data['order_id'])->find();
        $order_products_info = db('order_products_info')->where('order_products_info.order_id', $data['order_id'])->find();
//        $products_spec       = db('products_spec', config('database.zong'))->where('products_id', $order_products_info['products_id'])->where('scheme_id', $order_products_info['products_spec_scheme_id'])
//            ->field('scheme_id,products_id,id as only')
//            ->select();
        $products_spec = db('products_v2', config('database.zong'))->where('id', $order_products_info['products_id'])->field('id as scheme_id,id as products_id,id as only')->select();
        $res           = null;
        if (!empty($order_products_info) && empty($envelopes)) {
            foreach ($products_spec as $k => $item) {
                $products_spec[$k]['number'] = $order_products_info['products_quantity'];
            }
            $res = $products_spec;
        }
        
        r_date($res, 200);
    }
    
    /*
     * 计算价格
     */
    public function getValuation(DetailedOptionValue $detailedOptionValue, Common $common, Capital $capital) {
        $data = Authority::param(['data', 'id', 'types', 'capital_id']);
        if ($data['types'] == 4 || $data['types'] == 1) {
            $detailedValue = $common->newCapitalPrice($detailedOptionValue, $data['id'], json_decode($data['data'], true));
            if (!$detailedValue['code']) {
                r_date(null, 300, $detailedValue['msg']);
            }
            $detailedValueList = $detailedValue['data'];
        } else {
            if ($data['types'] == 0) {
                $product_chan               = db('product_chan')->where('product_id', $data['id'])->find();
                $detailedValueList['sum']   = $product_chan['prices'];
                $detailedValueList['price'] = $product_chan['price_rules'];
                $detailedValueList['unit']  = $product_chan['price_rules'];
                
            } elseif ($data['types'] == 2) {
                $capitalIdFind              = $capital->QueryOne($data['capital_id']);
                $detailedValueList['sum']   = $capitalIdFind['un_Price'];
                $detailedValueList['price'] = [];
                $detailedValueList['unit']  = $capitalIdFind['company'];
                
            }
        }
        
        r_date(['price' => $detailedValueList['sum'], 'artificial' => $detailedValueList['price'], 'unTitle' => $detailedValueList['unit']], 200);
    }
    
   
     /**
     * 新版基建报价界面显示
     */
    public function InfrastructureEcho(Envelopes $envelopes, ProductsSpec $productsSpec) {
        
        $data            = Authority::param(['envelopes_id']);
        $enableEnvelopes = $envelopes->where('envelopes_id', $data['envelopes_id'])->find();
        
        if ($enableEnvelopes->type == 1) {
            $envelopes = $envelopes->with(['CapitalList', 'CapitalList.specsList'])->where(['envelopes_id' => $data['envelopes_id']])->find();
        } else {
            $capital_listData = [];
            $envelopes        = $envelopes->with(['CapitalDatas', 'CapitalDatas.specsList'])->where(['envelopes_id' => $data['envelopes_id']])->find();
            
            foreach ($envelopes['CapitalDatas'] as $k => $o) {
                if (($o['products'] == 1 && $o['products_v2_spec'] != 0 && $o['is_product_choose'] == 1) || $o['products'] == 0) {
                    $capital_listData[] = $o;
                }
            }
            $envelopes['capital_list'] = $capital_listData;
            unset($envelopes['CapitalDatas']);
            
        }
        $orderList                    = db('order')->field('order.order_id,order.state,order_times.signing_time')->join('order_setting', 'order.order_id=order_setting.order_id', 'left')->join('order_times', 'order_times.order_id=order.order_id', 'left')->where('order.order_id', $envelopes['ordesr_id'])->find();
        $typeCapital['approval.type'] = array(['=', 6], ['=', 8], 'or');
        $capital_id                   = array_column($envelopes['capital_list'], 'capital_id');
        $approval                     = \db('approval', config('database.zong'))->field('bi_user.username,approval.relation_id,approval.approval_id')->join(config('database.zong')['database'] . '.bi_user', 'approval.nxt_id=bi_user.user_id', 'left')->where($typeCapital)->whereIn('approval.relation_id', $capital_id)->order('approval.approval_id desc')->select();
        $envelopes['approvalState']   = null;
        $approval_record              = \db('approval_record', config('database.zong'))->where('relation_id', $data['envelopes_id'])->where('type', 10)->order('id desc')->where('deleted_time', 0)->where('city_id', config('cityId'))->find();
        if (!empty($approval_record) && $approval_record['status'] == 0) {
            $change_value = $approval_record['change_value'];
        } else {
            $change_value = 0;
        }
        if (!empty($approval_record)) {
            $envelopes['approvalState'] = $approval_record['status'];
        }
        $res = array();
        $key = 'relation_id';
        foreach ($approval as $value) {
            //查看有没有重复项
            if (isset($res[$value[$key]])) {
                unset($value[$key]);
            } else {
                $res[$value[$key]] = $value;
            }
            
        }
        $manAllMoney      = 0;
        $allMoney         = 0;
        $envelopesProduct = Db::table('envelopes_product')->where('envelopes_product.envelopes_id', $envelopes['envelopes_id'])->where('state', 1)->select();
        $uniqueNumber     = [];
        foreach ($envelopesProduct as $l) {
            if ($l['products_type'] == 2) {
                $uniqueNumber[] = $l['uniqueNumber'];
            }
            foreach ($envelopes['capital_list'] as $k1 => $value1) {
                if (!empty($value1['uniqueNumber']) && $value1['uniqueNumber'] == $l['uniqueNumber']) {
                    $value1['schemeIds'] = $l['schemeIds'];
                }
            }
        }
        
        foreach ($envelopes['capital_list'] as $k => $value) {
            $value['isWarranty']         = 0;
            $warranty                    = null;
            $value['reasonForDeduction'] = empty($value['reasonForDeduction']) ? '' : $value['reasonForDeduction'];
            if ($value['capitalWarrantyYears'] > 0 || $value['warranty_years'] != '0.00') {
                $warranty = ['warrantYears' => $value['warranty_years'], 'warrantyText1' => $value['warranty_text_1'], 'exoneration' => $value['warranty_text_2'],];
                if ($value['zhi'] == 1) {
                    $value['isWarranty']      = 1;
                    $warranty['warrantYears'] = $value['capitalWarrantyYears'];
                }
                
            }
            $value['warranty']             = $warranty;
            $value['schemeIds']            = isset($value['schemeIds']) ? $value['schemeIds'] : 0;
            $typeCapital ['approval.type'] = 6;
            if ($value['giveType'] == 2) {
                $value['allMoney'] = $value['give_to_money'];
                if ($value['agency'] == 0) {
                    $manAllMoney += $value['give_to_money'];
                } else {
                    $allMoney += $value['give_to_money'];
                }
                
            }
     
            $value['artificialTag']     = 0;
            $value['smallOrderFeeType'] = 1;
            if ($value['smallOrderFee'] == '0.00') {
                $value['smallOrderFeeType'] = 2;
            }
            $price           = \db('detailed_option_value')->whereNUll('deleted_at')->where('is_enable', 1)->where('detailed_id', $value['projectId'])->where('condition', 2)->value('price');
            $okGive          = db('detailed')->where('detailed_id', $value['projectId'])->whereNull('deleted_at')->value('give');
            $value['okGive'] = 0;
            if ($okGive == 2) {
                $value['okGive'] = 1;
            }
            $rangePrice          = json_decode($price, true);
            $value['rangePrice'] = $rangePrice;
            if (!empty($value['sectionTitle'])) {
                $value['artificialTag'] = 1;
            }
            if ($value['products_square'] != 0) {
                $value['baseSquare'] = $value['square'] + $value['products_square'];
            }
            if ($value['isMerge'] == 1) {
                $value['isMerge']      = true;
                $value['projectMoney'] = $value['mergePrice'];
                $value['mergePrice']   = $value['un_Price'];
                
            } else {
                $value['isMerge'] = false;
            }
            $value['username'] = null;
            foreach ($res as $key => $item) {
                if ($key == $value['capital_id']) {
                    $value['username'] = $item['username'];
                }
            }
            
        }
        
        $capitalList         = $envelopes['capital_list'];
        $c_time              = time();
        $envelopes['coupon'] = null;
        $envelopes['sign']   = \db('sign')->where('order_id', $envelopes['ordesr_id'])->value('autograph');
        if (!empty($envelopes['main_id']) || !empty($envelopes['purchasing_id'])) {
            
            $id         = !empty($envelopes['main_id']) ? $envelopes['main_id'] : $envelopes['purchasing_id'];
            $couponList = db('coupon_user', config('database.zong'))->join('order', 'order.telephone=coupon_user.mobile', 'left')->join('coupon', 'coupon.id=coupon_user.coupon_id', 'left')->where('order.order_id', $envelopes['ordesr_id'])->where('coupon_user.id', $id)->field('coupon_user.id,coupon.coupon_title,(coupon.coupon_limit/100) as coupon_limit,coupon.coupon_use_type,coupon.coupon_type,(coupon.coupon_amount/100) as coupon_amount,coupon.coupon_discount,coupon.coupon_prize_quantity,coupon.coupon_prize_title,coupon.coupon_prize_unit,IF (coupon.coupon_expire_type = 1, coupon.coupon_expire_time_end, coupon_user.create_time + (coupon.coupon_expire_days * 86400)) as coupon_user_expire_e_time')->group('coupon_user.id')->find();
            
            $envelopes['couponSum'] = 0;
            if (empty($envelopes['sign'])) {
                if (empty($couponList) || $couponList['coupon_user_expire_e_time'] <= time()) {
                    
                    $coupon_user = db('coupon_user', config('database.zong'))->join('coupon', 'coupon.id=coupon_user.coupon_id', 'left')->where('coupon_user.id', $id)->field('coupon.coupon_type,concat(coupon.coupon_prize_title,"x",coupon.coupon_prize_quantity,coupon.coupon_prize_unit) as title')->find();
                    
                    $object = ['main_id' => 0, 'main_discount_money' => 0, 'purchasing_discount_money' => 0, 'purchasing_id' => 0, 'give_money' => $envelopes['give_money'] - $envelopes['main_discount_money'] - $envelopes['purchasing_discount_money']];
                    
                    if ($coupon_user['coupon_type'] == 3) {
                        
                        $give_b = explode(',', $envelopes['give_b']);
                        foreach ($give_b as $l => $o) {
                            if ($o == $coupon_user['title']) {
                                unset($give_b[$l]);
                            }
                        }
                        $object['give_b'] = implode($give_b, ',');
                        
                    }
                    
                    $envelopes['couponSum'] = $object['main_discount_money'] + $object['purchasing_discount_money'];
                    db('envelopes')->where(['envelopes_id' => $data['envelopes_id']])->update($object);
                    $envelopes['give_b'] = $object['give_b'];
                    
                }
            } else {
                
                $couponList = db('coupon_user', config('database.zong'))->join('coupon', 'coupon.id=coupon_user.coupon_id', 'left')->where('coupon_user.id', $id)->field('coupon_user.id,coupon.coupon_title,(coupon.coupon_limit/100) as coupon_limit,coupon.coupon_use_type,coupon.coupon_type,(coupon.coupon_amount/100) as coupon_amount,coupon.coupon_discount,coupon.coupon_prize_quantity,coupon.coupon_prize_title,coupon.coupon_prize_unit,IF (coupon.coupon_expire_type = 1, coupon.coupon_expire_time_end, coupon_user.create_time + (coupon.coupon_expire_days * 86400)) as coupon_user_expire_e_time')->group('coupon_user.id')->find();
            }
            $envelopes['give_money']          = round($envelopes['give_money'] - $envelopes['main_discount_money'], 2);
            $couponList['couponMoney']        = $envelopes['main_discount_money'] + $envelopes['purchasing_discount_money'];
            $arrayListNew[]                   = $couponList;
            $envelopes['coupon']              = $arrayListNew;
            $envelopes['purchasing_discount'] = round($envelopes['purchasing_discount'] - $envelopes['purchasing_discount_money'], 2);
        } else {
            $envelopes_coupon = db('envelopes_coupon')->where('envelopes_id', $data['envelopes_id'])->select();
            $id               = [];
            foreach ($envelopes_coupon as $item) {
                $id[] = !empty($item['main_id']) ? $item['main_id'] : $item['purchasing_id'];
            }
            if (!empty($id)) {
                $coupon_user = db('coupon_user', config('database.zong'))->join('coupon', 'coupon.id=coupon_user.coupon_id', 'left')->whereIn('coupon_user.id', implode(",", $id))->field('coupon_user.id,coupon.coupon_title,(coupon.coupon_limit/100) as coupon_limit,coupon.coupon_use_type,coupon.coupon_type,(coupon.coupon_amount/100) as coupon_amount,coupon.coupon_discount,coupon.coupon_prize_quantity,coupon.coupon_prize_title,coupon.coupon_prize_unit,IF (coupon.coupon_expire_type = 1, coupon.coupon_expire_time_end, coupon_user.create_time + (coupon.coupon_expire_days * 86400)) as coupon_user_expire_e_time')->group('coupon_user.id')->select();
                foreach ($coupon_user as $k => $li) {
                    foreach ($envelopes_coupon as $item) {
                        $id = !empty($item['main_id']) ? $item['main_id'] : $item['purchasing_id'];
                        
                        if ($li['id'] == $id) {
                            $coupon_user[$k]['couponMoney'] = $item['main_discount_money'] + $item['purchasing_discount_money'];
                        }
                    }
                    
                }
                $envelopes['coupon']              = $coupon_user;
                $envelopes['give_money']          = round($envelopes['give_money'] - array_sum(array_column($envelopes_coupon, 'main_discount_money')), 2);
                $envelopes['purchasing_discount'] = round($envelopes['purchasing_discount'] - array_sum(array_column($envelopes_coupon, 'purchasing_discount_money')), 2);
            }
            
            
        }
        
        $titleArray = [];
        
        $uniqueNumber = [];
        if (!empty($envelopesProduct)) {
            $envelopesProductCapital_list = $envelopes['capital_list'];
            foreach ($envelopesProduct as $l => $lis) {
                $products_title      = "";
                $products_id         = "";
                $products_spec_title = '';
                if ($lis['products_type'] == 1) {
                    $rows                = Db::connect(config('database.zong'))->table('products_spec')->field('products.*, products_spec.id as ids,products_spec.products_id,products_spec.products_spec_title,products_spec.products_spec_price,products_spec.products_spec_original_price,products_spec.products_spec_description,products_spec.discount_rate_1,products_spec.scheme_id,products_spec.discount_rate_2,products_spec.discount_rate_1,products.products_title')->join('products', 'products.id=products_spec.products_id', 'left')->where('products_spec.products_id', $lis['products_id'])->where('products_spec.scheme_id', $lis['schemeIds'])->find();
                    $products_spec_price = round($rows['products_spec_price'] / 100, 2);
                    $products_spec_title = $rows['products_spec_title'];
                    $ids                 = $rows['ids'];
                } else {
                    $uniqueNumber[] = $lis['uniqueNumber'];
                    $rows_v2        = Db::connect(config('database.zong'))->table('products_v2_spec')->field('products.*,products_v2_spec.*,products.id as ids')->join('products_v2 products', 'products.id=products_v2_spec.products_id', 'left')->where('products_v2_spec.products_id', $lis['products_id'])->where('products_v2_spec.is_required_module', 1)->select();
                    
                    $producCapitalList = $envelopes->producCapitalList;
                    if (!empty($producCapitalList)) {
                        $producCapitalListData = [];
                        foreach ($producCapitalList as $item) {
                            if ($item['uniqueNumber'] == $lis['uniqueNumber']) {
                                if ($item['isMerge'] == 1) {
                                    $item['isMerge']      = true;
                                    $item['projectMoney'] = $item['mergePrice'];
                                    $item['mergePrice']   = $item['un_Price'];
                                    
                                } else {
                                    $item['isMerge'] = false;
                                }
                                $producCapitalListData[] = $item;
                            }
                        }
                        $envelopesProductCapital_list = array_merge($envelopesProductCapital_list, $producCapitalListData);
                    }
                    $envelopesProductCapitalList = [];
                    foreach ($envelopesProductCapital_list as $k => $item) {
                        if ($item['unitVolume'] != 0 && $item['unique_status'] == 1) {
                            
                            $item['products_spec_price'] = round($lis['initial_sales_volume'] * $lis['products_unit_price'], 2);
//                            $item['products_spec_price'] = 0;
                        }
                        if ($item['products_v2_spec'] != 0) {
                            $item['schemeIds'] = isset($item['products_v2_spec']) ? $item['products_v2_spec'] : 0;
                        }
                        if ($item['uniqueNumber'] == $lis['uniqueNumber']) {
                            $envelopesProductCapitalList[] = $item;
                            if ($lis['sales_method'] == 1 && $item['unique_status'] == 1) {
                                $products_spec_price = round($item['products_spec_price'], 2);
                            }
                        }
                    }
                    $products_spec_title = implode(array_unique(array_column($envelopesProductCapitalList, 'categoryName')), ",");
//                    $products_spec_price = round(array_sum(array_column($rows_v2, 'products_spec_price')), 2);
                    if ($lis['sales_method'] == 2) {
                        $products_spec_price = round($lis['initial_sales_volume'] * $lis['products_unit_price'], 2);
                    }
//                    if ($lis['sales_method'] == 1) {
//                        $products_spec_price = round(array_sum(array_column($rows_v2, 'products_spec_price')), 2);
//                    }
                    $products_title = $rows_v2[0]['products_title'];
                    $products_id    = $rows_v2[0]['products_id'];
                    $ids            = $products_id;
                    
                }
                $list = [];
                if (!empty($envelopesProductCapitalList)) {
                    $title = array_unique(array_column($envelopesProductCapitalList, 'categoryName'));
                    foreach ($title as $value) {
                        $result = [];
                        foreach ($envelopesProductCapitalList as $key => $info) {
                            if ($value == $info['categoryName']) {
                                $isProductChoose = true;
                                if ($info['is_product_choose'] == 0) {
                                    $isProductChoose = false;
                                }
                                $unique_status = 1;
                                if ($info['unique_status'] == 0) {
                                    $unique_status = 2;
                                }
                                $info['isProductChoose'] = $isProductChoose;
                                $info['required']        = $unique_status;
                                $info['sales_method']    = $lis['sales_method'];
                                $info['specsList']       = [];
                                if (isset($info['specs_list']) && !empty($info['specs_list'])) {
                                    $info['specsList'] = $info['specs_list'];
                                    unset($info['specs_list']);
                                }
                                
                                $result['title']             = $info['categoryName'];
                                $result['required']          = $unique_status;
                                $result['sales_method']      = $lis['sales_method'];
                                $result['productsSpecPrice'] = $info['products_spec_price'];
                                $result['id']                = 0;
                                $result['data'][]            = $info;
                            }
                        }
                        $result['beLeftOver'] = 0;
//                        if ($unique_status == 1) {
//                            $result['beLeftOver'] += round(array_sum(array_column($result['data'], 'allMoney')) - $result['productsSpecPrice'], 2);
//                        }
                        if ($unique_status == 1 && $lis['sales_method'] == 1) {
                            $result['beLeftOver'] += round(array_sum(array_column($result['data'], 'allMoney')) - $result['productsSpecPrice'], 2);
                        } elseif ($unique_status == 1 && $lis['sales_method'] == 2) {
                            $result['beLeftOver']        = round(array_sum(array_column($result['data'], 'allMoney')) - $result['productsSpecPrice'], 2);
                            $result['productsSpecPrice'] = 0;
                        }
                        $list[] = $result;
                    }
                }
                $coutMainMoenyDiscount = 0;
                $coutMoenyDiscount     = 0;
                if ($lis['beLeftOver'] > 0) {
                    $coutMainMoenyDiscount = 0;
                    $coutMoenyDiscount     = 0;
                }
                if (empty($list)) {
                    $beLeftOver = $lis['beLeftOver'];
                } else {
                    $beLeftOver = round(array_sum(array_column($list, 'beLeftOver')), 2);
                }
                $titleArray[] = ['title' => !empty($rows) ? $rows['products_title'] : $products_title, 'products_id' => !empty($rows) ? $rows['products_id'] : $products_id, 'productsSpecTitle' => !empty($rows) ? $rows['products_spec_title'] : $products_spec_title, 'price' => isset($products_spec_price) ? $products_spec_price : 0, 'uniqueNumber' => $lis['uniqueNumber'], 'coutMainMoenyDiscount' => $coutMainMoenyDiscount, 'coutMoenyDiscount' => $coutMoenyDiscount, 'sales_method' => $lis['sales_method'], 'productsUnitPrice' => $lis['products_unit_price'], 'startingVolume' => $lis['initial_sales_volume'], 'initialSalesVolume' => $lis['sales_volume'], 'unit' => $lis['products_unit'], 'only' => $ids, 'beLeftOver' => $beLeftOver, 'list' => $list];
            }
            
            foreach ($envelopesProductCapital_list as $k => $item) {
                if (in_array($item['uniqueNumber'], $uniqueNumber)) {
                    unset($envelopesProductCapital_list[$k]);
                }
            }
            $envelopes['capital_list'] = $envelopesProductCapital_list;
        }
        $capitalListArray = [];
        $agency           = [];
        $sumlist          = [];
        foreach ($capitalList as $k => $item) {
            if ($item['agency'] == 1) {
                $agency[] = $item;
            } else {
                $sumlist[] = $item;
            }
        }
        
        $result   = array();
        $tageList = [];
        
        foreach ($envelopes['capital_list'] as $k => $v) {
            $v['specsList'] = $v['specs_list'];
            unset($v['specs_list']);
            $result[$v['categoryName']][] = $v;
        }
        foreach ($result as $k => $list) {
            $schemeTag['title'] = $k;
            $schemeTag['data']  = $result[$k];
            $tageList[]         = $schemeTag;
        }
        unset($envelopes['capital_list']);
        $envelopes['capital_list'] = $tageList;
        if (!empty($envelopes['give_b'])) {
            $envelopes['give_b'] = explode(',', $envelopes['give_b']);
        } else {
            $envelopes['give_b'] = null;
        }
        $envelopes_gantt_chart       = db('envelopes_gantt_chart')->where('order_id', $envelopes['ordesr_id'])->where('envelopes_id', $envelopes['envelopes_id'])->where('delete_time', 0)->value('type');
        $envelopes['ganttChartType'] = empty($envelopes_gantt_chart) ? 0 : $envelopes_gantt_chart;
//        if ($envelopes['capitalgo']) {
//            $envelopes['capitalgo'] = unserialize($envelopes['capitalgo']);
//        } else {
        $envelopes['capitalgo'] = null;

//        }
//质保卡
        $warranty_collection = \db('warranty_collection')->where('warranty_collection.envelopes_id', $envelopes['envelopes_id'])->where('warranty_collection.pro_types', 0)->join('warranty', 'warranty.id=warranty_collection.warranty_id', 'left')->where('warranty_collection.order_id', $envelopes['ordesr_id'])->field('warranty.title,warranty_collection.years,warranty_collection.type,warranty_collection.warranty_id,warranty_collection.id')->select();
        
        
        $envelopes['agencysum'] = round(array_sum(array_column($agency, 'allMoney')), 2);
        $envelopes['sumlist']   = round(array_sum(array_column($sumlist, 'allMoney')), 2);
//        foreach ($envelopes['coupon'] as $em) {
//            if ($envelopes['sumlist'] == 0 && !empty($envelopes['coupon']) && $em['coupon_type'] == 1) {
//
//                $envelopes['coupon'] = null;
//            }
//            if ($envelopes['agencysum'] == 0 && !empty($envelopes['coupon']) && $em['coupon_type'] == 2) {
//                $envelopes['coupon'] = null;
//            }
//
//            if ($envelopes['agencysum'] == 0 && !empty($envelopes['coupon']) && $em['coupon_type'] == 3 && $envelopes['sumlist'] == 0) {
//                $envelopes['coupon'] = null;
//            }
//        }
        
        if ($envelopes['products_main_discount_money'] != 0) {
            $envelopes['give_money'] = $envelopes['give_money'] - $envelopes['products_main_discount_money'];
        }
        if ($envelopes['products_purchasing_discount_money'] != 0) {
            $envelopes['purchasing_discount'] = $envelopes['purchasing_discount'] - $envelopes['products_purchasing_discount_money'];
        }
        $envelopes['give_money']          = (string)round($envelopes['give_money'] - $manAllMoney, 2);
        $envelopes['purchasing_discount'] = (string)round($envelopes['purchasing_discount'] - $allMoney, 2);
        $main_round_discount              = 0;
        $main_round_discount1             = 0;
        if ($envelopes['give_money'] >= $envelopes['main_round_discount']) {
            $main_round_discount     = 1;
            $envelopes['give_money'] = (string)round($envelopes['give_money'] - $envelopes['main_round_discount'], 2);
        }
        if ($envelopes['purchasing_discount'] >= $envelopes['purchasing_round_discount']) {
            $envelopes['purchasing_discount'] = (string)round($envelopes['purchasing_discount'] - $envelopes['purchasing_round_discount'], 2);
            $main_round_discount1             = 1;
            
        }
        if ($main_round_discount == 1 && $main_round_discount1 == 1) {
            $envelopes['main_round_discount'] = $envelopes['main_round_discount'] + $envelopes['purchasing_round_discount'];
        } elseif ($main_round_discount == 1 && $main_round_discount1 == 0) {
            $envelopes['main_round_discount'] = $envelopes['main_round_discount'];
        } elseif ($main_round_discount1 == 1 && $main_round_discount == 0) {
            $envelopes['main_round_discount'] = $envelopes['purchasing_round_discount'];
        }
        $envelopes['roundDiscountTitle'] = '提交报价后，系统会按支付节点计算抹零金额，最终签约金额在抹零优惠后可能会与报价预览产生偏差，实际金额以最终签约金额为准';
        if ($envelopes['main_round_discount'] > 0) {
            $envelopes['roundDiscountTitle'] = '提交报价后，系统会按节点计算抹零金额(抹零金额' . $envelopes['main_round_discount'] . '元)最终签约金额为扣减抹零后的金额。';
        }
        if ($orderList['signing_time'] == 0 || ($main_round_discount == 0 && $main_round_discount1 == 0)) {
            $envelopes['main_round_discount'] = 0;
        }
        $envelopes['coutMainMoenyDiscount'] = $envelopes['products_main_discount_money'];
        $envelopes['coutMoenyDiscount']     = $envelopes['products_purchasing_discount_money'];
        $envelopes['products']              = $titleArray;
        $envelopes['group']                 = $envelopes['groupss'];
        $envelopes['gong']                  = $envelopes['gong'] + $change_value;
        $duration                           = db('envelopes_gantt_chart')->where('order_id', $envelopes['ordesr_id'])->where('envelopes_id', $data['envelopes_id'])->where('delete_time', 0)->value('duration');
        if ($orderList['state'] < 4 && empty($duration)) {
            $envelopes['gong'] = 0;
        }
        $envelopes['order_list'] = $orderList;
        r_date(['company' => $envelopes, 'warranty_collection' => $warranty_collection, 'capitalList' => array_merge($capitalListArray)], 200);
    }
    
    /**
     * 成交后基检删除
     */
    public function TransactionDeletion(Approval $approval, Capital $capital, Common $common) {
        
        $data = Authority::param(['capital_id', 'quantity', 'reasonForDeduction']);
        db()->startTrans();
        try {
            $capitalFind = $capital->QueryOne($data['capital_id']);
            if ($capitalFind['acceptance'] != 0) {
                throw  new  Exception('该项目已验收不允许删除');
            }
            $state       = Db::table('order')->where('order_id', $capitalFind['ordesr_id'])->field('cleared_time,settlement_time')->find();
            $order_times = Db::table('order_times')->where('order_id', $capitalFind['ordesr_id'])->field('change_work_time')->find();
            if (!empty($state['cleared_time']) && $capitalFind['agency'] == 0) {
                r_date(null, 300, '主合同已结算无法操作');
            }
            if (!empty($state['settlement_time']) && $capitalFind['agency'] == 1) {
                r_date(null, 300, '代购已结算无法操作');
            }
            $order_setting                 = db('order_setting')->where('order_id', $capitalFind['ordesr_id'])->find();
            $personal_price                = Db::connect(config('database.db2'))->table('app_user_order_capital')->where('order_id', $capitalFind['ordesr_id'])->where('capital_id', $data['capital_id'])->whereNull('deleted_at')->field('sum(personal_price) as personal_price,sum(cooperation_price) as cooperation_price,sum(work_time) as work_time')->select();
            $orderCapital                  = Db::connect(config('database.zong'))->table('large_reimbursement')->where('order_id', $capitalFind['ordesr_id'])->where('status', 1)->sum('money');
            $reimbursement                 = db('reimbursement_relation')->join('reimbursement', 'reimbursement.id=reimbursement_relation.reimbursement_id', 'left')->whereIn('reimbursement.status', [1, 0, 3])->where('find_in_set(:id,reimbursement_relation.capital_id)', ['id' => $data['capital_id']])->field('reimbursement.status,reimbursement.order_id')->find();
            $envelopesFind                 = $capital->newcapitalProfit($capitalFind['ordesr_id'], $data['capital_id'], $capitalFind['envelopes_id'], $capitalFind['agency']);
            $appUserOrderCapitalLaborCosts = Db::connect(config('database.db2'))->table('app_user_order_capital_labor_costs')->where('order_id', $capitalFind['ordesr_id'])->where('capital_id', $data['capital_id'])->where('deleted_at', 0)->sum('personal_price');
            //判断有没有审核中的减项或减量
            $approvalRecordAll     = Db::connect(config('database.zong'))->table('approval_record')->where('approval_record.order_id', $capitalFind['ordesr_id'])->whereIn('type', [6, 9])->where('status', 0)->column('approval_record.relation_id');
            $approvals             = Db::connect(config('database.zong'))->table('approval')->where('approval.order_id', $capitalFind['ordesr_id'])->whereIn('type', [6, 8])->where('status', 0)->column('approval.relation_id');
            $capitalAll            = [];
            $capitals              = [];
            $approvalRecordAllList = array_merge($approvalRecordAll, $approvals);
            $mo                    = 1;
            if (!empty($approvalRecordAllList) && $order_times['change_work_time'] > 1720724400 && $mo == 0) {
                $capitalAll   = db('capital_minus_beforehand')->whereIn('capital_minus_beforehand.capital_id', $approvalRecordAllList)->where('delete_time', 0)->column('minus_id');
                $capitalAll   = db('capital_minus_beforehand')->whereIn('capital_minus_beforehand.minus_id', $capitalAll)->where('delete_time', 0)->column('capital_id');
                $detailedList = [1, 2];
                $detaileds    = db('capital')->join('detailed', 'detailed.detailed_id=capital.projectId', 'left')->whereIn('capital.capital_id', $approvalRecordAllList)->column('detailed.detailed_category_id');
                $capitals     = db('capital')->where(function ($quer) {
                    $quer->where('capital.approve', 0)->whereOr('capital.approve', 1)->whereOr('capital.approve', 2);
                })->where('capital.types', 1)->where('capital.enable', 1)->join('detailed', 'detailed.detailed_id=capital.projectId', 'left')->where('capital.ordesr_id', $capitalFind['ordesr_id'])->where(function ($query) use ($detailedList) {
                    foreach ($detailedList as $value) {
                        $query->whereOrRaw("FIND_IN_SET({$value}, detailed.reimbursement) > 0", [], 'string');
                    }
                })->whereIn('detailed.detailed_category_id', $detaileds)->field(['capital.capital_id'])->group('capital.capital_id')->select();
            }
            
            if (in_array($capitalFind['capital_id'], $approvalRecordAll)) {
                throw  new  Exception('有超限工费/减项正在审核，此时无法操作减项/减量，超限工费审核完成后可继续操作');
            }
            if (!empty($reimbursement) && $capitalFind['agency'] == 0 && $order_setting['capital_deduction_relation'] == 0) {
                if ($reimbursement['status'] == 0 || $reimbursement['status'] == 1 || $reimbursement['status'] == 3) {
                    throw  new  Exception('该清单关联的报销或请款已在审核中');
                }
            }
            if ($personal_price[0]['cooperation_price'] > 0) {
                throw  new  Exception('此清单有指派协作师傅，需要在人工设置处把工费清 0');
            }
            $approval_record = '';
            if (isset($data['quantity']) && $data['quantity'] != 0) {
                   // 将数字转换为字符串
                    $numStr = (string)$data['quantity'];
                    // 检查是否包含小数点
               if (strpos($numStr, '.') != false) {
                    // 分割整数和小数部分
                    $parts = explode('.', $numStr);
                    // 返回小数部分的长度
                    if (strlen($parts[1]) >= 3) {
                        throw  new  Exception('修改后的方量只能保留2位小数');
                    }
                }
                $title                = $capitalFind['class_b'] . '减少方量到(' . $data['quantity'] . ')';
                $signed               = 0;
                $status               = 3;
                $approvalType         = 9;
                $capitalFindMoney     = $capitalFind['un_Price'] * $data['quantity'];
                $sub_discounted_money = round($capitalFind['sub_discounted_money'] - (($data['quantity'] / $capitalFind['square']) * $capitalFind['sub_discounted_money']), 2);
                if ($appUserOrderCapitalLaborCosts == 0 && $personal_price[0]['personal_price'] > 0) {
                    throw  new  Exception('减项清单所派师傅标记工费/工时大于0，请师傅取消标记后减项。');
                }
            } else {
                $title                = $capitalFind['class_b'] . '项目减项(' . $this->us['username'] . ')';
                $signed               = 0;
                $approvalType         = 6;
                $status               = 1;
                $capitalFindMoney     = 0;
                $sub_discounted_money = $capitalFind['sub_discounted_money'];
                
                if ($appUserOrderCapitalLaborCosts > 0) {
                    throw  new  Exception('有工资快结支出，无法减项，可尝试减量');
                }
                if ($personal_price[0]['personal_price'] > 0) {
                    throw  new  Exception('减项清单所派师傅标记工费/工时大于0，请师傅取消标记后减项。');
                }
                
                if ($order_setting['capital_deduction_relation'] == 0 && $capitalFind['agency'] == 0 && $order_times['change_work_time'] > 1720724400 && $mo == 0) {
                    if (in_array($capitalFind['capital_id'], $capitalAll) || (in_array($capitalFind['capital_id'], array_column($capitals, 'capital_id')))) {
                        throw  new  Exception('有超限工费/减项正在审核，此时无法操作减项/减量，超限工费审核完成后可继续操作');
                    }
                    $LI = $common->allocateAvailableReimbursementLimits($capitalFind['ordesr_id'], $data['capital_id'], (string)round(($capitalFind['labor_cost'] + $capitalFind['labor_cost_material']) - $capitalFind['labor_cost_reimbursement'], 2), $capitalFind['projectId'], 1, $capitalFind['labor_cost_reimbursement']);
                    if ($LI['code'] == 300) {
                        throw  new  Exception($LI['msg']);
                    };
                    if ($LI['chao']['chao'] > 0) {
                        $approval_record = db('approval_record', config('database.zong'))->insertGetId(['city_id' => config('cityId'), 'order_id' => $capitalFind['ordesr_id'], 'type' => 6, 'change_value' => (string)$LI['chao']['chao'], 'relation_id' => $LI['chao']['List'][0]['capital_id'], 'created_time' => time()]);
                    }
                    if (!empty($LI['beforehand'])) {
                        db('capital_minus_beforehand')->insertAll($LI['beforehand']);
                    }
                }
                
            }
            if ($order_setting['max_discount_rate'] != 0 && $capitalFind['agency'] == 0 && ($envelopesFind['money'] + $capitalFindMoney) > 0 && $capitalFind['settlement_method'] !=3 && $capitalFind['settlement_method'] !=4) {
                if ((string)round(($envelopesFind['preferential'] - $sub_discounted_money) / ($envelopesFind['money'] + $capitalFindMoney), 2) * 100 > $order_setting['max_discount_rate']) {
                    throw  new  Exception('操作减项后,优惠将超过主合同最大优惠比例' . $order_setting['max_discount_rate'] . '%,不可减项!');
                }
            }
            
            if ($order_setting['max_agent_discount_rate'] != 0 && $capitalFind['agency'] == 1 && ($envelopesFind['money'] + $capitalFindMoney) > 0 && $capitalFind['settlement_method'] !=3 && $capitalFind['settlement_method'] !=4) {
                if ((string)round(($envelopesFind['preferential'] - $sub_discounted_money) / ($envelopesFind['money'] + $capitalFindMoney), 2) * 100 > $order_setting['max_agent_discount_rate']) {
                    throw  new  Exception('操作减项后,优惠将超过代购合同最大优惠比例' . $order_setting['max_agent_discount_rate'] . '%,不可减项!');
                }
            }
            if ($order_setting['capital_deduction_relation'] == 0 && $capitalFind['agency'] == 0) {
                if ($personal_price[0]['personal_price'] < $orderCapital) {
                    throw  new  Exception('不允许删除：大工地结算金额加过审大工地结算金额超过清单工资');
                }
            }
            
            if (!empty($reimbursement) && $capitalFind['agency'] == 1 && $data['quantity'] == 0 && $order_setting['capital_deduction_relation'] == 0) {
                throw  new  Exception('此清单已经支付过供应商款项，无法减项，只能减量');
            }
            
            if (empty($data['reasonForDeduction'])) {
                throw  new  Exception('原因不能为空');
            }
            $capitalUpdate = ['approve' => 3, 'modified_quantity' => $data['quantity'], 'reason_for_deduction' => $data['reasonForDeduction'], 'capital_id' => $data['capital_id'], 'signed' => $signed];
            $capital->isUpdate(true)->save($capitalUpdate);
            Db::connect(config('database.db2'))->table('agency_task')->where('capital_id', $data['capital_id'])->update(['status' => $status]);
            db()->commit();
            $this->inspect($capitalFind['ordesr_id'], $capitalFind['envelopes_id']);
            $approval->Reimbursement($data['capital_id'], $title, $this->us['username'], $approvalType, 1, $approval_record);
            if ($approvalType == 6 && $capitalFind['agency'] == 0 && $mo == 0) {
                $common->deleteRecalculatedCreditLimit($capitalFind['ordesr_id'], $data['capital_id'], 1);
            }
            sendOrder($capitalFind['ordesr_id']);
            r_date([], 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
    }
    
    /*
     * 获取减量最小放量
     */
    public function decrement(Capital $capital, Common $common) {
        $data = Authority::param(['capital_id', 'type']);
        //type等于减量等于2减项
        $number      = 0;
        $title       = '';
        $capitalFind = $capital->QueryOne($data['capital_id']);
        if ($data['type'] == 2) {
            if ($capitalFind['labor_cost'] + $capitalFind['labor_cost_material'] > 0) {
                $personal_price           = Db::table('app_user_order_capital_labor_costs')->where('order_id', $capitalFind['ordesr_id'])->where('capital_id', $capitalFind['capital_id'])->field('state,settlement_time,cleared_time')->sum('personal_price');
                $capital_minus_beforehand = Db::table('capital_minus_beforehand')->where('capital_id', $capitalFind['capital_id'])->where('delete_time', 0)->sum('beforehand_money');
                $number                   = (string)round((((($capitalFind['labor_cost'] + $capitalFind['labor_cost_material']) - $capitalFind['labor_cost_reimbursement'] - $personal_price - $capital_minus_beforehand)) / $capitalFind['labor_cost'] * $capitalFind['square']), 2);
                $number                   = $capitalFind['square'] - $number;
            }
            
        } else {
            if ($capitalFind['labor_cost'] + $capitalFind['labor_cost_material'] > 0) {
                $ko     = $common->allocateAvailableReimbursementLimits($capitalFind['ordesr_id'], $capitalFind['capital_id'], (string)round(($capitalFind['labor_cost'] + $capitalFind['labor_cost_material']) - $capitalFind['labor_cost_reimbursement'], 2), $capitalFind['projectId'], $data['type'], $capitalFind['labor_cost_reimbursement']);
                $number = isset($ko['chao']['chao']) ? $ko['chao']['chao'] : 0;
                if ($number == 0 && !empty($ko['beforehand'])) {
                    $title = '此清单产生过报销，如果仍然要减项，系统将会把你报销费用分摊至同笔报销清单中，请悉知';
                } elseif ($number > 0 && !empty($ko['beforehand'])) {
                    $title = '此清单产生过报销，如果仍然要减项，系统将会把报销费用分摊至同笔报销中，平摊后,其他清单将超出系统工费上限，你减项时还需要增加一个超限工费申请，请悉知';
                }
            }
        }
        
        r_date(['number' => $number, 'title' => $title], 200);
    }
    
    /**
     * 产品基检删除
     */
    public function TransactionProductDeletion(Approval $approval, Capital $capital) {
        $data = Authority::param(['capital_id', 'reasonForDeduction', 'quantity']);
        
        db()->startTrans();
        try {
            $capitalFind = $capital->QueryOne($data['capital_id']);
            
            $state = Db::table('order')->where('order_id', $capitalFind['ordesr_id'])->field('state,settlement_time,cleared_time')->find();
            
            if (!empty($state['cleared_time']) && $capitalFind['agency'] == 0) {
                r_date(null, 300, '主合同已结算无法操作');
            }
            if (!empty($state['settlement_time']) && $capitalFind['agency'] == 1) {
                r_date(null, 300, '代购已结算无法操作');
            }
            
            $capitalUpdate = ['up_products' => 1, 'up_products_time' => time(), 'capital_id' => $data['capital_id']];
            if ($state['state'] > 3) {
                $work_time = Db::connect(config('database.db2'))->table('app_user_order_capital')->whereNull('deleted_at')->where('capital_id', $data['capital_id'])->value('work_time');
                if ($work_time != 0) {
                    throw  new  Exception('师傅工时不为0无法删除');
                }
                if ($capitalFind['acceptance'] != 0) {
                    throw  new  Exception('该项目已验收不允许删除');
                }
                $order_setting  = db('order_setting')->where('order_id', $capitalFind['ordesr_id'])->find();
                $personal_price = Db::connect(config('database.db2'))->table('app_user_order_capital')->where('order_id', $capitalFind['ordesr_id'])->whereNull('deleted_at')->sum('personal_price');
                $orderCapital   = Db::connect(config('database.zong'))->table('large_reimbursement')->where('order_id', $capitalFind['ordesr_id'])->where('status', 1)->sum('money');
                if ($personal_price < $orderCapital && $order_setting['capital_deduction_relation'] == 0) {
                    throw  new  Exception('不允许删除：大工地结算金额加过审大工地结算金额超过清单工资');
                }
                if ($data['quantity'] == '') {
                    $title         = $capitalFind['class_b'] . '项目减项(' . $this->us['username'] . ')';
                    $signed        = $capitalFind['signed'];
                    $approvalType  = 6;
                    $capitalUpdate = ['approve' => 3, 'reason_for_deduction' => $data['reasonForDeduction'], 'capital_id' => $data['capital_id'], 'signed' => $signed];
                } else {
                    $capitalUpdate = ['products_square' => $data['quantity'], 'capital_id' => $data['capital_id']];
                }
                
            } else {
                if ($data['quantity'] == '') {
                    $capitalUpdate = ['up_products' => 1, 'capital_id' => $data['capital_id'], 'up_products_time' => time()];
                } else {
                    $capitalUpdate = ['products_square' => $data['quantity'], 'capital_id' => $data['capital_id']];
                }
            }
            $capital->isUpdate(true)->save($capitalUpdate);
            db()->commit();
            if ($state['state'] > 3 && $data['quantity'] == '') {
                $this->inspect($capitalFind['ordesr_id'], $capitalFind['envelopes_id']);
                Db::connect(config('database.db2'))->table('agency_task')->where('capital_id', $data['capital_id'])->update(['status' => 3]);
                $approval->Reimbursement($data['capital_id'], $title, $this->us['username'], $approvalType);
            }
            if ($state['state'] < 4) {
                $order_setting = db('order_setting')->where('order_id', $capitalFind['ordesr_id'])->find();
                $this->guanlifei($order_setting, $capitalFind['ordesr_id'], $capitalFind['envelopes_id']);
            }
            sendOrder($capitalFind['ordesr_id']);
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
    }
    
    
    /**
     * 基检套餐删除
     */
    public function productsDelete(Capital $capital, Approval $approval, Common $common) {
        $data = Authority::param(['uniqueNumber', 'envelopesId']);
        
        $orderIds = $capital->where('uniqueNumber', $data['uniqueNumber'])->order('capital_id asc')->where('envelopes_id', $data['envelopesId'])->select();
        if ($orderIds[0]['approve'] == 3) {
            r_date(null, 300, '该项目已提交,请等待审核');
        }
        $sub_discounted_money = array_sum(array_column($orderIds, 'sub_discounted_money'));
        $state                = Db::table('order')->where('order_id', $orderIds[0]['ordesr_id'])->field('state,settlement_time,cleared_time')->find();
        $order_times          = Db::table('order_times')->where('order_id', $orderIds[0]['ordesr_id'])->field('change_work_time')->find();
        $agencyList           = [];
        $manList              = [];
        foreach ($orderIds as $i) {
            if ($i['agency'] == 1 && $i['enable'] == 1 && $i['types'] == 1) {
                $agencyList[] = $i;
            }
            if ($i['agency'] == 0 && $i['enable'] == 1 && $i['types'] == 1) {
                $manList[] = $i;
            }
        }
        if (!empty($state['settlement_time']) && !empty($agencyList)) {
            r_date(null, 300, '代购已结算无法操作');
        }
        if (!empty($state['cleared_time']) && !empty($manList)) {
            r_date(null, 300, '主合同已结算无法操作');
        }
        if ($state['state'] > 7) {
            r_date(null, 300, '订单状态不对,无法操作');
        }
        $capitalCount = $capital->where('uniqueNumber', '<>', $data['uniqueNumber'])->where('envelopes_id', $data['envelopesId'])->where('types', 1)->where('enable', 1)->where('give', 0)->count();
        if ($capitalCount == 0) {
            r_date(null, 300, '必须保留一个项目');
        }
        $order_setting         = db('order_setting')->where('order_id', $orderIds[0]['ordesr_id'])->find();
        $approvalRecordAll     = Db::connect(config('database.zong'))->table('approval_record')->where('approval_record.order_id', $orderIds[0]['ordesr_id'])->whereIn('type', [6, 9])->where('status', 0)->column('approval_record.relation_id');
        $approvals             = Db::connect(config('database.zong'))->table('approval')->where('approval.order_id', $orderIds[0]['ordesr_id'])->whereIn('type', [6, 8])->where('status', 0)->column('approval.relation_id');
        $capitalAll            = [];
        $approvalRecordAllList = array_merge($approvalRecordAll, $approvals);
        if (!empty($approvalRecordAllList)) {
            $capitalAll = db('capital_minus_beforehand')->whereIn('capital_minus_beforehand.capital_id', $approvalRecordAllList)->where('delete_time', 0)->column('minus_id');
            $capitalAll = db('capital_minus_beforehand')->whereIn('capital_minus_beforehand.minus_id', $capitalAll)->where('delete_time', 0)->column('capital_id');
        }
        $approval_record = [];
        db()->startTrans();
        try {
            $mo = 1;
            if ($order_times['change_work_time'] > 1720724400 && $mo == 0) {
                foreach ($orderIds as $o) {
                    if ($o['enable'] == 1 && $o['types'] == 1) {
                        if (in_array($o['capital_id'], $capitalAll)) {
                            throw  new  Exception('有超限工费正在审核，此时无法操作减项/减量，超限工费审核完成后可继续操作(' . $o['class_b'] . '/' . $o['square'] . ')');
                        }
                        $reimbursement = db('reimbursement_relation')->join('reimbursement', 'reimbursement.id=reimbursement_relation.reimbursement_id', 'left')->where('reimbursement.status', 0)->where('find_in_set(:id,reimbursement_relation.capital_id)', ['id' => $o['capital_id']])->field('reimbursement.status,reimbursement.order_id')->find();
                        if (!empty($reimbursement) && $o['agency'] == 0 && $order_setting['capital_deduction_relation'] == 0) {
                            if ($reimbursement['status'] == 0) {
                                throw  new  Exception('该清单关联的报销或请款已在审核中(' . $o['class_b'] . '/' . $o['square'] . ')');
                            }
                        }
                        $personal_price = Db::connect(config('database.db2'))->table('app_user_order_capital')->where('order_id', $o['ordesr_id'])->where('capital_id', $o['capital_id'])->whereNull('deleted_at')->field('sum(personal_price) as personal_price,sum(cooperation_price) as cooperation_price,sum(work_time) as work_time')->select();
                        if ($personal_price[0]['cooperation_price'] > 0) {
                            throw  new  Exception('此清单有指派协作师傅，需要在人工设置处把工费清 0(' . $o['class_b'] . '/' . $o['square'] . ')');
                        }
                        if ($personal_price[0]['personal_price'] > 0) {
                            throw  new  Exception('减项清单所派师傅标记工费/工时大于0，请师傅取消标记后减项。(' . $o['class_b'] . '/' . $o['square'] . ')');
                        }
                        $appUserOrderCapitalLaborCosts = Db::connect(config('database.db2'))->table('app_user_order_capital_labor_costs')->where('order_id', $o['ordesr_id'])->where('capital_id', $o['capital_id'])->where('deleted_at', 0)->sum('personal_price');
                        if ($appUserOrderCapitalLaborCosts > 0) {
                            throw  new  Exception('有工资快结支出，无法减项，可尝试减量(' . $o['class_b'] . '/' . $o['square'] . ')');
                        }
                        if ($order_setting['capital_deduction_relation'] == 0 && $o['labor_cost_reimbursement'] > 0 && $o['agency'] == 0) {
                            $LI = $common->allocateAvailableReimbursementLimits($o['ordesr_id'], $o['capital_id'], (string)round(($o['labor_cost'] + $o['labor_cost_material']) - $o['labor_cost_reimbursement'], 2), $o['projectId'], 3, $o['labor_cost_reimbursement'], $data['uniqueNumber']);
                            if ($LI['code'] == 300) {
                                throw  new  Exception($LI['msg'] . '(' . $o['class_b'] . '/' . $o['square'] . ')');
                            }
                            if ($LI['chao']['chao'] > 0) {
                                $approval_record[] = ['city_id' => config('cityId'), 'order_id' => $o['ordesr_id'], 'type' => 6, 'change_value' => (string)$LI['chao']['chao'], 'relation_id' => $LI['chao']['List'][0]['capital_id'], 'created_time' => time(), 'labor_cost' => $LI['chao']['List'][0]['labor_cost']];
                            }
                            if (!empty($LI['beforehand'])) {
                                db('capital_minus_beforehand')->insertAll($LI['beforehand']);
                            }
                        }
                    }
                }
            }
            
            $envelopesProduct          = db('envelopes_product')->where('uniqueNumber', $data['uniqueNumber'])->where('envelopes_id', $data['envelopesId'])->where('state', 1)->find();
            $products_spec_price       = db('envelopes_product')->where('uniqueNumber', '<>', $data['uniqueNumber'])->where('envelopes_id', $data['envelopesId'])->where('state', 1)->select();
            $manproducts_spec_price    = 0;
            $agencyproducts_spec_price = 0;
            foreach ($products_spec_price as $item) {
                if ($item['products_main_expense'] == 0) {
                    $agencyproducts_spec_price += $item['products_spec_price'];
                }
                if ($item['products_main_expense'] != 0) {
                    $manproducts_spec_price += $item['products_spec_price'];
                }
            }
            if ($envelopesProduct['products_main_expense'] == 0) {
                $agency = 3;
            }
            if ($envelopesProduct['products_main_expense'] != 0) {
                $agency = 4;
            }
            $order_setting = db('order_setting')->where('order_id', $orderIds[0]['ordesr_id'])->find();
            $capitalProfit = $capital->newcapitalProfit($orderIds[0]['ordesr_id'], 0, $envelopesProduct['envelopes_id'], $agency);
            
            if ($state['state'] < 4) {
                $capitalUpdate              = ['types' => 2, 'untime' => time()];
                $envelopes                  = db('envelopes')->where('envelopes_id', $envelopesProduct['envelopes_id'])->find();
                $productsMainContract       = $envelopes['products_main_discount_money'] - $envelopesProduct['products_main_discount_money'];
                $productsPurchasingContract = $envelopes['products_purchasing_discount_money'] - $envelopesProduct['products_purchasing_discount_money'];
                $give_money                 = $envelopes['give_money'] - $envelopesProduct['products_main_discount_money'];
                $purchasing_discount        = $envelopes['purchasing_discount'] - $envelopesProduct['products_purchasing_discount_money'];
                
                db('envelopes')->where('envelopes_id', $envelopesProduct['envelopes_id'])->update(['give_money' => $give_money, 'purchasing_discount' => $purchasing_discount, 'products_main_discount_money' => $productsMainContract, 'products_purchasing_discount_money' => $productsPurchasingContract]);
                
                db('envelopes_product')->where('uniqueNumber', $data['uniqueNumber'])->update(['state' => 2]);
            } else {
                if ($order_setting['max_discount_rate'] != 0 && $agency == 4 && ($capitalProfit['money'] + $manproducts_spec_price) != 0) {
                    if ((string)round(($capitalProfit['preferential'] - $sub_discounted_money) / ($capitalProfit['money'] + $manproducts_spec_price), 3) * 100 > $order_setting['max_discount_rate']) {
                        throw  new  Exception('操作减项后,优惠将超过主合同单最大优惠比例' . $order_setting['max_discount_rate'] . '%,不可减项!');
                    }
                }
                
                if ($order_setting['max_agent_discount_rate'] != 0 && $agency == 3 && ($capitalProfit['money'] + $agencyproducts_spec_price) != 0) {
                    if ((string)round(($capitalProfit['preferential'] - $sub_discounted_money) / ($capitalProfit['money'] + $agencyproducts_spec_price), 3) * 100 > $order_setting['max_agent_discount_rate']) {
                        throw  new  Exception('操作减项后,优惠将超过代购合同最大优惠比例' . $order_setting['max_agent_discount_rate'] . '%,不可减项!');
                    }
                }
                $approvalList = [];
                if (!empty($approval_record)) {
                    $result = [];
                    foreach ($approval_record as $item) {
                        $relationId = $item['relation_id'];
                        // 检查$result数组中是否已经有这个relation_id的条目
                        if (!isset($result[$relationId])) {
                            // 如果没有，则添加一个新条目，并初始化change_value为当前条目的值
                            $result[$relationId] = ['relation_id' => $relationId, 'city_id' => $item['city_id'], 'order_id' => $item['order_id'], 'type' => $item['type'], 'created_time' => $item['created_time'], 'change_value' => $item['change_value'], // 假设我们只保留累加后的change_value
                                'labor_cost' => $item['labor_cost'], // 假设我们只保留累加后的change_valu
                                // 如果需要保留其他信息，比如created_time（可能需要逻辑决定使用哪个时间），可以添加这里
                            ];
                        } else {
                            // 如果已经存在，则累加change_value
                            $result[$relationId]['change_value'] += $item['change_value'];
                        }
                    }
                    $indexedResult = array_values($result);
                    foreach ($indexedResult as $k => $item) {
                        $approvalList[] = db('approval_record', config('database.zong'))->insertGetId(['city_id' => $item['city_id'], 'order_id' => $item['order_id'], 'type' => 6, 'change_value' => $item['change_value'], 'relation_id' => $item['relation_id'], 'created_time' => $item['created_time']]);
                        
                    }
                }
                $capitalUpdate = ['approve' => 3];
                if ($envelopesProduct['products_type'] == 1) {
                    $title = Db::connect(config('database.zong'))->table('products')->where('id', $envelopesProduct['products_id'])->value('products_title');
                } else {
                    $title = Db::connect(config('database.zong'))->table('products_v2')->where('id', $envelopesProduct['products_id'])->value('products_title');
                }
                Db::connect(config('database.db2'))->table('agency_task')->whereIn('capital_id', array_column($orderIds, 'capital_id'))->update(['status' => 1]);
                db('envelopes_product')->where('uniqueNumber', $data['uniqueNumber'])->update(['approval' => 2]);
            }
            $capital->where('uniqueNumber', $data['uniqueNumber'])->where('enable', 1)->where('types', 1)->update($capitalUpdate);
            db()->commit();
            if ($state['state'] > 3) {
                $approval->Reimbursement($data['uniqueNumber'], $title, $this->us['username'], 10, 1, empty($approvalList) ? '' : implode(',', $approvalList));
                if ($mo == 0) {
                    $common->deleteRecalculatedCreditLimit($orderIds[0]['ordesr_id'], 0, 1, 3, $data['uniqueNumber']);
                }
                
                
            } else {
                $this->guanlifei($order_setting, $orderIds[0]['ordesr_id'], $envelopesProduct['envelopes_id']);
            }
            r_date(null, 200);
            
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
        
        
    }
    
     /**
     * 基检增项
     */
    public function AdditionalItem(Common $common, Capital $capital, DetailedOptionValue $detailedOptionValue, CapitalValue $capitalValue, Envelopes $envelopes, VisaForm $visaForm, EnvelopeRecords $envelopeRecords) {
        $data                     = Authority::param(['company', 'order_id', 'envelopes_id', 'gong', 'purchasin_money', 'paymentMethod', 'productList']);
        $parameter                = Request::instance()->post();
        $visa_form                = db('visa_form')->where('order_id', $data['order_id'])->whereNUll('signing_time')->count();
        $orderList                = db('order')->field('personal.num,order.created_time,order.cleared_time,order.settlement_time,order_aggregate.main_price,order_aggregate.agent_price,contract.con_time')->join('personal', 'order.tui_jian=personal.personal_id', 'left')->join('order_aggregate', 'order_aggregate.order_id=order.order_id', 'left')->join('contract', 'contract.orders_id=order.order_id', 'left')->where('order.order_id', $data['order_id'])->find(); 
        $orderList['isNeedPaper'] = 0;
        if ($visa_form != 0 && $orderList['isNeedPaper'] == 0) {
            r_date(null, 300, '上一个签证单没有签字，不能发起新的签证单');
        }
        $envelopesType = db('envelopes')->where('envelopes_id', $data['envelopes_id'])->value('type');
        if ($envelopesType == 0) {
            r_date(null, 300, '该报价清单不是终选报价，不能增项');
        }
        db()->startTrans();
        $created_time = $orderList['created_time'];
        $capitalSort  = db('capital')->where('envelopes_id', $data['envelopes_id'])->max('sort');
        try {
            $ids                   = [];
            $toPrice               = 0;
            $givePrice             = 0;
            $giveMainPrice         = 0;
            $agent_amount          = 0;
            $p1                    = 0;
            $p                     = 0;
            $mainMaterials         = [];//套餐中时候存在主材
            $agencyMaterials       = [];//套餐中时候存在代购主材
            $totalPriceOfPackage   = 0;
            $productToMonry        = 0;
            $productOld            = [];//老产品
            $productNew            = [];//新产品
            $Newproduct            = [];
            $NewtNowPackageProduct = [];
            $BuyItNowPackage       = isset($parameter['productList']) ? json_decode($parameter['productList'], true) : null;
            $countZong=0;
            if ($BuyItNowPackage) {
                foreach ($BuyItNowPackage as $k => $item) {
                    $NewtNowPackageProduct[$k]['id']    = '';
                    $NewtNowPackageProduct[$k]['title'] = $item['title'];
                    $listArray                          = [];
                    if (!empty($item['list'])) {
                        foreach ($item['list'] as $k1 => $v) {
                            $countZong+=1;
                            if (!empty($v['data'])) {
                                foreach ($v['data'] as $ke => $value) {
                                    $value['categoryName']        = $v['title'];
                                    $value['products_spec_price'] = 0;
                                    if ($value['sales_method'] == 2 && $value['required'] == 1) {
                                        $value['products_spec_price'] = $item['initialSalesVolume'] * $item['productsUnitPrice'];
                                    }
                                    if ($value['sales_method'] == 1 && $value['required'] == 1) {
                                        $value['products_spec_price'] = $v['productsSpecPrice'];
                                    }
                                    $value['initialSalesVolume']  = isset($item['initialSalesVolume']) ? $item['initialSalesVolume'] : 0;
                                    $value['startingVolume']      = isset($item['startingVolume']) ? $item['startingVolume'] : 0;
                                    $value['products_unit_price'] = isset($item['productsUnitPrice']) ? $item['productsUnitPrice'] : 0;
                                    $value['sales_method']        = isset($item['sales_method']) ? $item['sales_method'] : 1;;
                                    $value['products_v2_spec'] = $value['schemeIds'];
                                    $value['fang']             = $value['square'];
                                    $value['NewProducts']      = 1;
                                    $value['product_id']       = $value['projectId'];
                                    $value['unit']             = $value['company'];
                                    $value['products']         = 1;
                                    $value['type']             = 1;
                                    $value['prices']           = $value['projectMoney'];
                                    $value['sectionTitle']     = isset($value['sectionTitle']) ? $value['sectionTitle'] : '';
                                    $listArray[]               = $value;
                                }
                            }
                            
                        }
                    }
                    $NewtNowPackageProduct[$k]['data'] = $listArray;
                }
            }
            $companyLists = [];
            $company      = json_decode($data['company'], true);
            if ($company) {
                if (!empty($company)) {
                    foreach ($company as $ke => $value) {
                        $value['NewProducts']         = 0;
                        $value['sales_method']        = 0;
                        $value['products_spec_price'] = isset($value['productsSpecPrice']) ? $value['productsSpecPrice'] : 0;
                        foreach ($value['data'] as $l => $item) {
                            $countZong+=1;
                            $value['data'][$l]['categoryName'] = $value['title'];
                        }
                        
                        $companyLists[] = $value;
                    }
                    
                }
            }
            $op = array_merge($companyLists, $Newproduct);
            $op = array_merge($op, $NewtNowPackageProduct);
            if (empty($op)) {
                r_date(null, 300, '请添加清单');
            }
            $purchasin_money=0;
           //直售价格
           $zhuZhiSho    = 0;
           $daiZhiSho    = 0;
           $zhuZhiShoChan=0;
           $daiZhiShoChan=0;
            foreach ($op as $ke => $v) {
                if (!empty($v['data'])) {
                    foreach ($v['data'] as $value) {
                        if (!isset($value['specsList'])) {
                            throw new Exception('请编辑清单包后提交');
                        }
                        if ($value['agency'] == 1 && !empty($orderList['settlement_time'])) {
                            throw new Exception('代购已经结算，无法增项');
                        }
                        if ($value['agency'] == 0 && !empty($orderList['cleared_time'])) {
                            throw new Exception('主合同已经结算，无法增项');
                        }
                        if (($orderList['main_price'] == 0 && !empty($orderList['settlement_time']) && $value['agency'] == 0) || ($orderList['agent_price'] == 0 && !empty($orderList['cleared_time']) && $value['agency'] == 1)) {
                            throw new Exception('订单已完结无法增项');
                        }
                        $ValueList                          = $value['specsList'];
                        $value['fang']                      = $value['square'];
                        $value['product_id']                = $value['projectId'];
                        $value['unit']                      = $value['company'];
                        $value['type']                      = 0;
                        $value['envelopes_id']              = $data['envelopes_id'];
                        $value["unitVolume"]                = isset($value['increment_per_unit_volume']) ? $value['increment_per_unit_volume'] : 0;
                        $value["increment_per_unit_volume"] = isset($value['increment_per_unit_volume']) ? $value['increment_per_unit_volume'] : 0;
                        $value["startingVolume"]            = isset($value['unit_volume']) ? $value['unit_volume'] : 0;;
                        $value["unit_volume"] = isset($value['unit_volume']) ? $value['unit_volume'] : 0;;
                        $value["sales_volume"] = isset($value['sales_volume']) ? $value['sales_volume'] : 0;;
                        $value["prices"]              = isset($value['prices']) ? $value['prices'] : 0;
                        $value["products_unit_price"] = isset($value['products_unit_price']) ? $value['products_unit_price'] : 0;
                        if ($value['types'] == 4) {
                            $ValueId      = array_column($ValueList, 'option_value_id');
                            $CapitalPrice = $common->newCapitalPrice($detailedOptionValue, $value['product_id'], $ValueId,$value['fang']);
                            if (!$CapitalPrice['code']) {
                                throw new Exception($CapitalPrice['msg']);
                            }
                          
                            $fangs                      = -1;
                            $small_order_fee_square_min = 0;
                            $small_order_fee_square_max = 0;
                            if (!empty($CapitalPrice['data']['small_order_fee']) && ($value['products'] == 0 || ($value['products'] == 1 && $value['required'] == 2 && $value['isProductChoose'])) && $value['smallOrderFeeType'] == 1) {
//                                $IsSmallOrderFee    = db('capital')->where('types', 1)->where('projectId', $value['product_id'])->where('enable', 1)->where(function ($quer) {
//                                    $quer->where('products', 0)->whereOr(['products' => 1, 'unique_status' => 0, 'is_product_choose' => 1]);
//                                })->where('envelopes_id', $data['envelopes_id'])->where('small_order_fee', '>', 0)->find();
                                $smallOrderFeePrice = 0;
//                                if (empty($IsSmallOrderFee)) {
                                foreach ($CapitalPrice['data']['small_order_fee'] as $k => $value2) {
                                    if ($value2['start'] <= $value['fang'] && $value2['end'] > $value['fang']) {
                                        $small_order_fee_square_min = $value2['start'];
                                        $smallOrderFeePrice         = $value2['value'];
                                        $small_order_fee_square_max = $value2['end'];
                                    }
                                }
                                if ($smallOrderFeePrice > 0) {
                                    $fangs = $value['fang'];
//                                        foreach ($y as $k1e => $v1) {
//                                            if (!empty($v1['data'])) {
//                                                foreach ($v1['data'] as $kj => $value1) {
//                                                    if (($value1['products'] == 0 || ($value1['products'] == 1 && $value1['required'] == 2 && $value1['isProductChoose'])) && $value1['projectId'] == $value['product_id']) {
//                                                        $fangs = $value['fang'];
//                                                        unset($y[$k1e]['data'][$kj]);
//                                                    }
//                                                }
//                                                $y[$k1e]['data'] = array_merge($y[$k1e]['data']);
//                                            }
//                                        }
                                }
//                                }
                                
                            }
                            $CapitalPriceSection      = $capital->priceSection($CapitalPrice['data']['price'], $CapitalPrice['data']['artificial'], $CapitalPrice['data']['sum'], $CapitalPrice['data']['sumMast'], $value['fang'], $value['company'], $CapitalPrice['data']['small_order_fee'], $fangs);
                            $data['labor_cost_price'] = $CapitalPriceSection[0];
                            $data['sumMast']          = $CapitalPriceSection[2];
                            $data['small_order_fee']  = $CapitalPriceSection[5];
                            if ($data['small_order_fee'] == 0) {
                                $small_order_fee_square_min = 0;
                                $small_order_fee_square_max = 0;
                            } 
                            $data['base_cost']         = 0;
                            $data['is_product_choose'] = 0;
                            if ($value['agency'] == 1) {
                                $data['labor_cost_price'] = $CapitalPrice['data']['sumMast'] * $value['fang'];
                                $data['base_cost']        = $CapitalPrice['data']['base_cost'];
                                $data['sumMast']          = $CapitalPrice['data']['sumMast'];
                            }
                            if (isset($value['products']) && $value['products'] == 1 && $value['NewProducts'] == 0) {
                                $data['toPrice']       = $value['allMoney'];
                                $data['unique_status'] = 0;
                                $productOld []         = ['toPrice' => $data['toPrice'], 'agency' => $value['agency'], 'products_id' => $value['products_id'], 'productType' => 1, 'schemeIds' => $value['schemeIds'], 'uniqueNumber' => $value['uniqueNumber'], 'isGiveUpProducts' => $value['isGiveUpProducts'],];
                                if ($value['agency'] == 0) {
                                    $mainMaterials[] = $v;
                                }
                                if ($value['agency'] == 1) {
                                    $agencyMaterials[] = $v;
                                }
                                $plan_id = db('scheme_project', config('database.zong'))->Join('scheme_master', 'scheme_master.plan_id=scheme_project.plan_id', 'left')->where('scheme_project.plan_id', $value['schemeIds'])->select();
                                foreach ($plan_id as $item) {
                                    if ($item['settlement_method'] == 2 && $item['projectId'] == $value['product_id']) {
                                        $data['labor_cost_price'] = $item['fixed_price'];
                                        $data['sumMast']          = round($item['fixed_price'] / $value['fang'], 2);
                                    }
                                    
                                }
                                $data['mast_rule']     = '';
                                $value['sectionTitle'] = '';
                            } elseif (isset($value['products']) && $value['products'] == 1 && $value['NewProducts'] == 1) {
                                if ($value['required'] == 1) {
                                    $value['unique_status']    = 1;
                                    $data['is_product_choose'] = 1;
                                    if ($value['agency'] == 0) {
                                        $mainMaterials[] = $value;
                                    }
                                    if ($value['agency'] == 1) {
                                        $agencyMaterials[] = $value;
                                    }
                                    $data['toPrice'] = $CapitalPriceSection[3] * $value['fang'];
                                    $productNew []   = ['toPrice' => $data['toPrice'], 'agency' => $value['agency'], 'products_id' => $value['products_id'], 'schemeIds' => $value['schemeIds'], 'sales_method' => $value['sales_method'], 'uniqueNumber' => $value['uniqueNumber'], 'sales_volume' => $value['initialSalesVolume'],//销售方量
                                        'startingVolume' => $value['startingVolume'],//起始销售方量
                                        'products_unit_price' => $value['products_unit_price'], 'isGiveUpProducts' => 0, 'productType' => 2,];
                                }
                                if ($value['required'] == 2 && $value['isProductChoose']) {
                                    $value['unique_status']    = 0;
                                    $data['is_product_choose'] = 1;
                                    $data['toPrice']           = $CapitalPriceSection[3] * $value['fang'];
                                }
                                $data['mast_rule'] = '';
                                
                            } else {
                                $data['toPrice']   = $CapitalPriceSection[3] * $value['fang'];
                                $data['mast_rule'] = $CapitalPriceSection[4];
                                
                            }
                            $data['toPrice']       = $data['toPrice'] + $data['small_order_fee']; 
                            $data['settlement_method'] = empty($CapitalPrice['data']['salesCommission'])?1:$CapitalPrice['data']['salesCommission'][0]['settlement_method'];
                            $data['fixed_rate'] =  empty($CapitalPrice['data']['salesCommission'])?0:$CapitalPrice['data']['salesCommission'][0]['fixed_rate'];
                            $data['fixed_cost'] =  empty($CapitalPrice['data']['salesCommission'])?0:$CapitalPrice['data']['salesCommission'][0]['fixed_cost'];
                            $data['sum']           = $CapitalPriceSection[3];
                            $data['price']         = $CapitalPrice['data']['price'];
                            $data['groupss'] = $CapitalPrice['data']['group'];
                            $data['artificial']    = $CapitalPrice['data']['artificial'];
                            $value['artificial']   = $CapitalPrice['data']['sum'];
                            $data['categoryTitle'] = $CapitalPrice['data']['categoryTitle'];
                            $data['base_contract_price'] = $CapitalPrice['data']['base_contract_price'];
                            $data['giveType'] = $value['giveType'];
                           
                            if ($value['isWarranty'] == 1) {
                                $data['warrantYears']   = $CapitalPrice['data']['warrantYears'];
                                $data['warrantyText1']  = time();
                                $data['exoneration']    = strtotime(date("Y-m-d", strtotime("+" . ($CapitalPrice['data']['warrantYears'] * 12) . " months")));
                                $data['warrantyReason'] = '';
                                $value['zhi']           = 1;
                            } else {
                                $data['warrantYears']   = $CapitalPrice['data']['warrantYears'];
                                $data['warrantyText1']  = 0;
                                $data['exoneration']    = 0;
                                $data['warrantyReason'] = isset($value['warrantyReason']) ? $value['warrantyReason'] : '';
                                $value['zhi']           = 0;
                            }
                            $data['products_v2_spec'] = isset($value['products_v2_spec']) ? $value['products_v2_spec'] : 0;
                            $value['enable']          = 1;
                            if ($created_time > 1660150844 && $orderList['isNeedPaper'] == 0) {
                                $value['enable'] = 0;
                            }
                            $isFou = 0;
                            if ($data['small_order_fee'] > 0) {
                                $isFou = 1;
                            }
                            $data['small_order_fee_square_min'] = $small_order_fee_square_min;
                            $data['small_order_fee_square_max'] = $small_order_fee_square_max;
                            if($value['agency'] == 1 && $CapitalPrice['data']['userId'] !=0){
                                $data['toPrice']           =$value['allMoney'];
                                $data['labor_cost_price'] =0;
                                $data['sum'] =$value['projectMoney'];
                                $value['artificial'] = $value['projectMoney'];
                                $data['artificial'] = $value['projectMoney'];
                                $data['base_cost']        = 0;
                                $data['sumMast']          = 0;
                            }
                          
                            if($countZong==1 && ($data['settlement_method']==3 || $data['settlement_method']==4) && ($parameter['purchasin_money'] !=0 || $parameter['give_money'] !=0)){
                                
                                throw new Exception("根据公司销售政策，直售清单（店长固定提点清单）无法优惠，请勿设置优惠");
                            }
                           
                            if ($value['agency'] == 0) {
                                if (($data['settlement_method'] == 3 || $data['settlement_method'] == 4) && $value['products'] == 0) {
                                    $zhuZhiSho += $data['toPrice'];
                                }
                                 if ( ($data['settlement_method'] == 3 || $data['settlement_method']== 4) && $value['products'] != 0) {
                                     $zhuZhiShoChan += $data['toPrice'];
                                }
                            }
                            if ($value['agency'] == 1) {
                                if (($data['settlement_method'] == 3 || $data['settlement_method'] == 4) && $value['products'] == 0) {
                                    $daiZhiSho += $data['toPrice'];
                                }
                                if ( ($data['settlement_method'] == 3 || $data['settlement_method'] == 4) && $value['products'] != 0) {
                                     $daiZhiShoChan += $data['toPrice'];
                                
                                }
                            }
                            if(($value['products'] == 0 || ($value['products'] == 1 && $value['NewProducts'] == 1 && ( $value['required'] == 2 && $value['isProductChoose'])|| $value['required'] == 1) || ($value['products'] == 1 && $value['NewProducts'] == 0)) && $value['agency'] == 1){
                                $purchasin_money +=  $data['toPrice'];
                            }
                            $id                                 = $capital->newlyAdded($data, $value, 1, $capitalSort + ($ke + 1), 0, $isFou);
                            if (($value['products'] == 1 && ((isset($value['unique_status']) && $value['unique_status'] == 1) || (isset($value['unique_status']) && $value['unique_status'] == 0 && $value['isProductChoose'] == 1))) || $value['products'] == 0) {
                                $idFind = $id;
                            }
                            foreach ($ValueList as $item) {
                                $capitalValue->Add($item, $id);
                            }
                            if ($value['agency'] == 1 && $value['giveType'] == 0) {
                                $p1 += $CapitalPriceSection[1];
                            }
                            if ($value['agency'] == 0 && $value['giveType'] == 0) {
                                $p += $CapitalPriceSection[1];
                            }
                            
                        } else {
                            if ($value['types'] == 0) {
                                $product_chan = db('product_chan')->where('product_id', $value['product_id'])->find();
                                $type         = 0;
                            } elseif ($value['types'] == 1) {
                                $product_chan = db('detailed')->where('detailed_id', $value['product_id'])->find();
                                $type         = 1;
                            } elseif ($value['types'] == 2) {
                                $product_chan['artificial'] = $value['price'];
                                $product_chan['rmakes']     = isset($value['remarks']) ? $value['remarks'] : '';
                                $type                       = 2;
                            }
                            $idFind = $capital->oldAdded($product_chan, $value, $data['order_id'], $type, 1);
                        }
                        
                        $ids[] = $idFind;
                        if ($value['giveType'] == 2) {
                            if ($value['agency'] == 1) {
                                $givePrice += $data['toPrice'] + $data['small_order_fee'];
                            } else {
                                $giveMainPrice += $data['toPrice'];
                            }
                        }
                        if ($value['agency'] == 0 && $value['products'] == 0 && $value['giveType'] == 0) {
                            $toPrice += round($data['toPrice'], 2);
                        }
                        if ($value['agency'] == 1 && $value['products'] == 0 && $value['giveType'] == 0) {
                            $agent_amount += round($data['toPrice'], 2);
                        }
                    }
                }
            }
            $order_setting = db('order_setting')->where('order_id', $data['order_id'])->find();
            if (empty($ids)) {
                throw new Exception("数据错误");
            }
            $purchasin_money=(string)round(($purchasin_money * ($order_setting['max_agent_expense_rate'] / 100)), 2);
            if($purchasin_money >0 && $parameter['dgmanagementMoney']==0){
                throw new Exception("代购合同管理费错误请编辑后重试");
            }
            $ids           = array_unique($ids);
            $capital_id    = $ids;
            $array         = [];
            $envelopesFind = $capital->capitalProfit($data['order_id'], 0, $data['envelopes_id']);
            $duration      = 0;
            if ($data['gong'] != 0) {
                $duration = $data['gong'];
                if ($created_time < 1660150844 || $orderList['isNeedPaper'] == 1) {
                    $envelopes->isUpdate(true)->save(['envelopes_id' => $data['envelopes_id'], 'gong' => $data['gong'] + $envelopesFind['gong']]);
                    array_push($array, ['previous_quantity' => $envelopesFind['gong'], 'post_quantity' => $data['gong'], 'reason' => '增项修改工期', 'type' => 1, 'envelopes_id' => $data['envelopes_id']]);
                    $startup = \db('startup')->where('orders_id', $data['order_id'])->find();
                    
                    if (!empty($startup['sta_time'])) {
                        $work_calendar = db('work_calendar', config('database.zong'))->where('data_string', '>=', date('Y-m-d', $startup['sta_time']))->where('is_work', 1)->order('data_string ACS')->limit($data['gong'] + $envelopesFind['gong'])->select();
                        $up_time       = strtotime($work_calendar[count($work_calendar) - 1]['data_string'] . ' 23:59:59');
                        \db('app_user_order', config('database.db2'))->where('order_id', $data['order_id'])->update(['plan_work_time' => ($data['gong'] + $envelopesFind['gong']) * 24 * 60 * 60, 'plan_end_at' => $up_time]);
                        \db('startup')->where('orders_id', $data['order_id'])->update(['up_time' => $up_time]);
                    }
                    
                }
                
            }
            $money     = 0;
            $mainMoney = 0;
            if (isset($parameter['managementMoney']) && $parameter['managementMoney'] != 0) {
                $mainMoney += $parameter['managementMoney'];
                if ($created_time < 1660150844 || $orderList['isNeedPaper'] == 1) {
                    $expense = round($envelopesFind['expense'] + $parameter['managementMoney'], 2);
                    $envelopes->isUpdate(true)->save(['envelopes_id' => $data['envelopes_id'], 'expense' => $expense]);
                    array_push($array, ['previous_quantity' => $envelopesFind['expense'], 'post_quantity' => $expense, 'reason' => '增项修改管主合同理费', 'type' => 2, 'envelopes_id' => $data['envelopes_id']]);
                }
            }
            if (isset($parameter['dgmanagementMoney']) && $parameter['dgmanagementMoney'] != 0) {
//                $mainMoney += $parameter['dgmanagementMoney'];
                $money += $parameter['dgmanagementMoney'];
                if ($created_time < 1660150844 || $orderList['isNeedPaper'] == 1) {
                    $expense1 = round($envelopesFind['purchasing_expense'] + $parameter['dgmanagementMoney'], 2);
                    $envelopes->isUpdate(true)->save(['envelopes_id' => $data['envelopes_id'], 'purchasing_expense' => $expense1]);
                    array_push($array, ['previous_quantity' => $envelopesFind['purchasing_expense'], 'post_quantity' => $expense1, 'reason' => '增项修改增加代购合同理费', 'type' => 4, 'envelopes_id' => $data['envelopes_id']]);
                }
            }
            if (!empty($productOld) || !empty($productNew)) {
                $coutMainMoeny = array_merge($productOld, $productNew);
                if (!empty($coutMainMoeny)) {
                    $title = array_unique(array_column($coutMainMoeny, 'uniqueNumber'));
                    foreach ($title as $key => $info) {
                        $money1   = 0;
                        $allMoney = [];
                        foreach ($coutMainMoeny as $item) {
                            if ($info == $item['uniqueNumber']) {
                                $result[$key]['products_id']         = $item['products_id'];
                                $result[$key]['schemeIds']           = $item['schemeIds'];
                                $result[$key]['sales_method']        = $item['sales_method'];
                                $result[$key]['sales_volume']        = isset($item['sales_volume']) ? $item['sales_volume'] : 0;
                                $result[$key]['startingVolume']      = isset($item['startingVolume']) ? $item['startingVolume'] : 0;
                                $result[$key]['products_unit_price'] = isset($item['products_unit_price']) ? $item['products_unit_price'] : 0;
                                $result[$key]['productType']         = $item['productType'];
                                $money1                              += $item['toPrice'];
                                $allMoney[]                          = ['toPrice' => $item['toPrice'], 'agency' => $item['agency'], 'isGiveUpProducts' => $item['isGiveUpProducts'],];
                            }
                        }
                        
                        if ($result[$key]['productType'] == 1) {
                            $products_spec                       = db('products_spec', config('database.zong'))->where('products_id', $result[$key]['products_id'])->join('products', 'products.id=products_spec.products_id', 'left')->join('unit', 'products.products_unit=unit.id', 'left')->where('scheme_id', $result[$key]['schemeIds'])->field('products_spec.*,products.*,unit.title as unitTitle')->find();
                            $productToMonry                      += round($products_spec['products_spec_price'] / 100, 2);
                            $beLeftOver                          = round($money, 2) - round($products_spec['products_spec_price'] / 100, 2);
                            $result[$key]['products_spec_price'] = round($products_spec['products_spec_price'] / 100, 2);
                            $title                               = $products_spec['products_title'] . '-' . $products_spec['products_spec_title'];
                            $products_spec_price                 = round($products_spec['products_spec_price'] / 100, 2);
                            $products_spec_title                 = $products_spec['products_spec_title'];
                            $products_unit                       = $products_spec['unitTitle'];
                        } elseif ($result[$key]['productType'] == 2) {
                            $products_spec = db('products_v2_spec', config('database.zong'))->field('products.*,products_v2_spec.*,products.id as ids,unit.title as unitTitle,products.sales_method,products.products_unit_price')->join('products_v2 products', 'products.id=products_v2_spec.products_id', 'left')->join('unit', 'products.products_unit=unit.id', 'left')->where('products_v2_spec.products_id', $result[$key]['products_id'])->where('products_v2_spec.is_required_module', 1)->select();
                            $products_spec_priceSum=0;
                            foreach ($products_spec as $lp) {
                                if ($lp['sales_method'] == 2) {
                                    $productToMonry      += round($lp['products_unit_price'] * $result[$key]['sales_volume'], 2);
                                    $products_spec_price = round($lp['products_unit_price'] * $result[$key]['sales_volume'], 2);
                                    $products_spec_priceSum +=$products_spec_price;
                                } else {
                                    $productToMonry      += round($lp['products_spec_price'], 2);
                                    $products_spec_price = round($lp['products_spec_price'], 2);
                                    $products_spec_priceSum +=$products_spec_price;
                                }
                            }
                            $products_spec_price=$products_spec_priceSum;
                            //                        $products_spec_price = round(array_sum(array_column($products_spec, 'products_spec_price')), 2);
                            $beLeftOver          = round($money1 - $products_spec_priceSum, 2);
                            $title               = $products_spec[0]['products_title'];
                            $products_spec_title = "";
                            $products_unit       = $products_spec[0]['unitTitle'];
                        };
                        $coutMainMoenyDiscountMoney  = 0;
                        $coutMoenyDiscountMoney      = 0;
                        $products_main_expense       = 0;
                        $products_purchasing_expense = 0;
                        
                        if ($beLeftOver >= 0) {
                            $last_man_datas = array_column($allMoney, 'toPrice');
                            array_multisort($last_man_datas, SORT_ASC, $allMoney);
                            $Proportion = 0;
                            foreach ($allMoney as $k => $m) {
                                if ($k != count($allMoney) - 1) {
//                                    $Proportion                 += bcdiv($m['toPrice'], $money1, 2);
                                    $allMoney[$k]['proportion'] = bcdiv($m['toPrice'], $money1, 2);
                                }
                                if ($m['agency'] == 1 && $m['isGiveUpProducts'] == 0) {
                                    $products_purchasing_expense += $m['toPrice'];
                                }
                                if ($m['agency'] == 0 && $m['isGiveUpProducts'] == 0) {
                                    $products_main_expense += $m['toPrice'];
                                }
                                
                            }
                            foreach ($allMoney as $k => $m) {
                                if ($k == count($allMoney) - 1) {
                                    $allMoney[$k]['proportionAmount'] = bcsub($beLeftOver, $Proportion, 3);
                                } else {
                                    $allMoney[$k]['proportionAmount'] = bcmul($beLeftOver, $m['proportion'], 2);
                                    $Proportion                       += $allMoney[$k]['proportionAmount'];
                                }
                            }
                            foreach ($allMoney as $k => $j) {
                                if ($j['agency'] == 1) {
                                    $coutMoenyDiscountMoney += $j['proportionAmount'];
                                }
                                if ($j['agency'] == 0) {
                                    $coutMainMoenyDiscountMoney += $j['proportionAmount'];
                                }
                            }
                        } else {
                            throw new Exception("产品配置出现问题，请截图联系供应链【西蒙】【产品" . $result[$key]['products_id'] . "】");
                        }
                        $result[$key]['money']                       = $money1;
                        $result[$key]['beLeftOver']                  = $beLeftOver;
                        $result[$key]['coutMainMoenyDiscount']       = $coutMainMoenyDiscountMoney;
                        $result[$key]['coutMoenyDiscount']           = $coutMoenyDiscountMoney;
                        $result[$key]['products_main_expense']       = round(($products_main_expense * $order_setting['max_expense_rate']) / 100, 2);
                        $result[$key]['products_purchasing_expense'] = round(($products_purchasing_expense * $order_setting['max_agent_expense_rate']) / 100, 2);
                        $result[$key]['uniqueNumber']                = $info;
                        $result[$key]['title']                       = $title;
                        $result[$key]['products_spec_price']         = $products_spec_price;
                        $result[$key]['products_spec_title']         = $products_spec_title;
                        $result[$key]['products_unit']               = $products_unit;
                    }
                    
                    $result = array_values($result);
                    
                }
                
            }
            $manProductToMonry          = 0;
            $agentProductToMonry        = 0;
            $coutMoenyDiscountMoney     = 0;
            $coutMainMoenyDiscountMoney = 0;
            if (!empty($result)) {
                if (!empty(array_column($result, 'coutMainMoenyDiscount'))) {
                    $coutMainMoenyDiscountMoney += array_sum(array_column($result, 'coutMainMoenyDiscount'));
                    
                }
                
                if (!empty(array_column($result, 'coutMoenyDiscount'))) {
                    $coutMoenyDiscountMoney += array_sum(array_column($result, 'coutMoenyDiscount'));
                    
                }
                foreach ($result as $k => $o) {
                    if ($o['products_main_expense'] != 0) {
                        $manProductToMonry += $o['products_spec_price'];
                    }
                    if ($o['products_main_expense'] == 0) {
                        $agentProductToMonry += $o['products_spec_price'];
                    }
                }
                
            }
         
            if ($order_setting['max_discount_rate'] != 0 && ($toPrice != 0 || $manProductToMonry != 0 || $giveMainPrice != 0)) {
                $mancapitalProfit = $capital->newcapitalProfit($data['order_id'], 0, $data['envelopes_id'], 0);
               
                if($manProductToMonry >0){
                    $manProductToMonry=$manProductToMonry-$zhuZhiShoChan;
                }
                if($agentProductToMonry==0){
                   $manProductToMonry=$manProductToMonry-$daiZhiShoChan; 
                }
                if ( ($mancapitalProfit['money'] + $manProductToMonry + $toPrice + $giveMainPrice-$zhuZhiSho)>0 && (string)round(($mancapitalProfit['preferential'] + $parameter['give_money'] + $giveMainPrice) / ($mancapitalProfit['money'] + $manProductToMonry + $toPrice + $giveMainPrice-$zhuZhiSho), 3) * 100 > $order_setting['max_discount_rate']) {
                    throw  new  Exception('操作增项后,优惠将超过主合同最大优惠比例' . $order_setting['max_discount_rate'] . '%（报价中包含直售清单（店长固定提点清单），此类清单无法优惠，设置优惠金额时，请按照合同总价减去直售清单售价后的金额来设置）,不可增项!');
                }
                if ($manProductToMonry + $toPrice + $giveMainPrice-$zhuZhiSho< $parameter['give_money']) {
                    throw  new  Exception('主合同优惠金额需要小于增项金额（直售清单不算，公司政策直售清单不参与优惠），请修改优惠');
                }
            }
            if ($order_setting['max_agent_discount_rate'] != 0 && ($agent_amount != 0 || $agentProductToMonry != 0 || $givePrice != 0)) {
                $capitalProfit = $capital->newcapitalProfit($data['order_id'], 0, $data['envelopes_id'], 1);
                if($agentProductToMonry >0){
                    $agentProductToMonry=$agentProductToMonry-$daiZhiShoChan;
                }
                if($agentProductToMonry==0){
                   $agentProductToMonry=$agentProductToMonry-$zhuZhiShoChan; 
                }
                if (($capitalProfit['money'] + $agent_amount + $agentProductToMonry + $givePrice-$daiZhiSho) >0 && (string)round(($capitalProfit['preferential'] + $parameter['purchasin_money'] + $givePrice) / ($capitalProfit['money'] + $agent_amount + $agentProductToMonry + $givePrice-$daiZhiSho), 3) * 100 > $order_setting['max_agent_discount_rate']) {
                    throw  new  Exception('操作增项后,优惠将超过代购合同最大优惠比例' . $order_setting['max_agent_discount_rate'] . '%（报价中包含直售清单（店长固定提点清单），此类清单无法优惠，设置优惠金额时，请按照合同总价减去直售清单售价后的金额来设置）,不可增项!');
                }
                if ($agent_amount + $agentProductToMonry + $givePrice-$daiZhiSho< $parameter['purchasin_money']) {
                    throw  new  Exception('代购优惠金额需要小于增项金额（直售清单不算，公司政策直售清单不参与优惠），请修改优惠');
                }
            }
            if($agent_amount == 0 && $agentProductToMonry == 0 && $givePrice == 0 && $parameter['purchasin_money']>0){
               throw  new  Exception('非纯主材标品，代购不可增加优惠'); 
            }
          
            // $GiftDiscounts       = db('capital')->where(['types' => 1, 'enable' => 1])->where('give', 2)->where('ordesr_id', $data['order_id'])->field('if(agency=1,to_price,0) as agency,if(agency=0,to_price,0) as man')->select();
            // $GiftDiscountsAgency = 0;
            // $GiftDiscountsMan    = 0;
            // if ($GiftDiscounts) {
            //     $GiftDiscountsAgency = empty($GiftDiscounts[0]['agency']) ? 0 : $GiftDiscounts[0]['agency'];
            //     $GiftDiscountsMan    = empty($GiftDiscounts[0]['man']) ? 0 : $GiftDiscounts[0]['man'];
            // }
            if ((($manProductToMonry + $toPrice) + ($agentProductToMonry + $agent_amount)) + $mainMoney + $money - ($parameter['give_money'] + $parameter['purchasin_money']) < 0) {
                throw  new  Exception('增项总金额不能小于0');
            }
            
            
            $agencySum = 0;
            $manySum   = 0;
            //赠送优惠
            if ($givePrice != 0) {
                if ($created_time < 1660150844 || $orderList['isNeedPaper'] == 1) {
                    array_push($array, ['previous_quantity' => $envelopesFind['purchasing_discount'], 'post_quantity' => $givePrice + $envelopesFind['purchasing_discount'], 'type' => 5, 'reason' => '赠送变更代购主材优惠金额', 'envelopes_id' => $data['envelopes_id']]);
                }
                $agencySum += $givePrice;
            }
            //app添加的优惠
            if (isset($parameter['purchasin_money']) && $parameter['purchasin_money'] != 0) {
                if ($created_time < 1660150844 || $orderList['isNeedPaper'] == 1) {
                    array_push($array, ['previous_quantity' => $envelopesFind['purchasing_discount'] + $agencySum, 'post_quantity' => $parameter['purchasin_money'] + $envelopesFind['purchasing_discount'] + $agencySum, 'type' => 5, 'reason' => '变更代购主材优惠金额', 'envelopes_id' => $data['envelopes_id']]);
                }
                $agencySum += $parameter['purchasin_money'];
            }
            if ($giveMainPrice != 0) {
                if ($created_time < 1660150844 || $orderList['isNeedPaper'] == 1) {
                    array_push($array, ['previous_quantity' => $envelopesFind['give_money'], 'post_quantity' => $giveMainPrice + $envelopesFind['give_money'], 'type' => 3, 'reason' => '赠送变更主材优惠金额', 'envelopes_id' => $data['envelopes_id']]);
                }
                $manySum += $giveMainPrice;
            }
            //app添加的优惠
            if (isset($parameter['give_money']) && $parameter['give_money'] != 0) {
                if ($created_time < 1660150844 || $orderList['isNeedPaper'] == 1) {
                    array_push($array, ['previous_quantity' => $envelopesFind['give_money'] + $manySum, 'post_quantity' => $parameter['give_money'] + $envelopesFind['give_money'] + $manySum, 'type' => 3, 'reason' => '变更主材优惠金额', 'envelopes_id' => $data['envelopes_id']]);
                }
                $manySum += $parameter['give_money'];
            }
            
            if ($created_time < 1660150844 || $orderList['isNeedPaper'] == 1) {
                $oi = ['give_money' => +$envelopesFind['give_money'] + $envelopesFind['products_main_discount_money'] + $manySum + $coutMainMoenyDiscountMoney,//优惠金额
                    'purchasing_discount' => $agencySum + $coutMoenyDiscountMoney + $envelopesFind['purchasing_discount'] + $envelopesFind['products_purchasing_discount_money'], 'products_main_discount_money' => !empty($result) ? array_sum(array_column($result, 'coutMainMoenyDiscount')) : 0, 'products_purchasing_discount_money' => !empty($result) ? array_sum(array_column($result, 'coutMoenyDiscount')) : 0, 'envelopes_id' => $data['envelopes_id']];
                $envelopes->isUpdate(true)->save($oi);
            }
            if (!empty($result)) {
                $resultListArray = [];
                foreach ($result as $k => $o) {
                    $resultListArray[$k]['products_main_discount_money']       = $o['coutMainMoenyDiscount'];
                    $resultListArray[$k]['products_purchasing_discount_money'] = $o['coutMoenyDiscount'];
                    $resultListArray[$k]['money']                              = $o['money'];
                    $resultListArray[$k]['beLeftOver']                         = $o['beLeftOver'];
                    $resultListArray[$k]['uniqueNumber']                       = $o['uniqueNumber'];
                    $resultListArray[$k]['products_id']                        = $o['products_id'];
                    $resultListArray[$k]['state']                              = 2;
                    $resultListArray[$k]['products_type']                      = $o['productType'];
                    $resultListArray[$k]['sales_method']                       = $o['sales_method'];
                    if ($created_time < 1660150844 || $orderList['isNeedPaper'] == 1) {
                        $resultListArray[$k]['state'] = 1;
                    }
                    $resultListArray[$k]['envelopes_id']                = $data['envelopes_id'];
                    $resultListArray[$k]['crtime']                      = time();
                    $resultListArray[$k]['products_spec_price']         = $o['products_spec_price'];
                    $resultListArray[$k]['schemeIds']                   = $o['schemeIds'];
                    $resultListArray[$k]['title']                       = $o['title'];
                    $resultListArray[$k]['products_spec_title']         = $o['products_spec_title'];
                    $resultListArray[$k]['products_unit']               = $o['products_unit'];
                    $resultListArray[$k]['products_main_expense']       = $o['products_main_expense'];
                    $resultListArray[$k]['products_purchasing_expense'] = $o['products_purchasing_expense'];
                    $resultListArray[$k]['sales_volume']                = $o['sales_volume'];
                    $resultListArray[$k]['products_unit_price']         = $o['products_unit_price'];
                    $resultListArray[$k]['approval']                    = 1;
                     //套餐一口价优惠平均分配
                     $capital->averagePackage($o);
                }
                db('envelopes_product')->insertAll($resultListArray);
            }
            if (!empty($array)) {
                $envelopeRecords->record($array);
            }
            $assemblyAdditions = $capital->assemblyAdditions($ids, $parameter['give_money'], $parameter['purchasin_money'], $order_setting, $mainMoney, $money,1);
            $visaForm->addList($data['order_id'], $capital_id, '', '', 1, $money, $mainMoney, $parameter['give_money'], $parameter['purchasin_money'], $duration, $data['paymentMethod'], $coutMainMoenyDiscountMoney, $coutMoenyDiscountMoney);
            if ($created_time < 1660150844 || $orderList['isNeedPaper'] == 1) {
                \db('capital_schedule')->insert(['order_id' => $data['order_id'], 'types' => 1, 'main_amount' => $toPrice + $mainMoney - $parameter['give_money'], 'agent_amount' => $agent_amount + $money - $parameter['purchasin_money'], 'change_time' => time(), 'capital_ids' => implode(',', $ids)]);
            }
            db()->commit();
//            $this->pdf->put($data['order_id'], 1, 0);
            $this->inspect($data['order_id'], $data['envelopes_id']);
            if($orderList['con_time']<1748534400){
                $this->auxiliaryInteractive($capital_id,$data['order_id']);
            }
         
            sendOrder($data['order_id']);
            r_date($id, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
        
    }
    
    /*
     * 基建签证单
     */
    public function VisaDetails(VisaForm $visaForm) {
        $data    = Authority::param(['order_id', 'autograph']);
        $VisaPng = $visaForm->VisaDetails($data['order_id'], $data['autograph']);
        r_date($VisaPng, 200);
        
    }
    
    /*
    * 修改报价清单
    */
    public function QuotationList(Capital $capital) {
        $data = Authority::param(['give_remarks', 'capital_id', 'class_b']);
        $capital->isUpdate(true)->save(['class_b' => $data['class_b'], 'projectRemark' => $data['give_remarks'], 'capital_id' => $data['capital_id']]);
        r_date(null, 200);
    }
    
    /*
    * 修改报价分组名称
    */
    public function QuotationListEdit(Capital $capital) {
        $data       = Authority::param(['capital_id', 'categoryName']);
        $capital_id = json_decode($data['capital_id'], true);
        $capital->whereIn('capital_id', $capital_id)->update(['categoryName' => $data['categoryName']]);
        r_date(null, 200);
    }
    
    
    /*
    * 修改报价清单
    */
    public function MarkCollaboration(Capital $capital) {
        
        $data = Authority::param(['cooperation', 'capital_id']);
        $capital->isUpdate(true)->save(['cooperation' => $data['cooperation'], 'capital_id', $data['capital_id']]);
        r_date(null, 200);
    }
    
    
    /*
     * 数据同步
     */
    public function DataMatching(DetailedOptionValue $detailedOptionValue, Common $common, Capital $capital) {
        $data = Authority::param(['projectJson']);
        
        $list = null;
        
        if (!empty(json_decode($data['projectJson'], true))) {
            $projectJson = json_decode($data['projectJson'], true);
            $list        = $detailedOptionValue->matching($projectJson);
            foreach ($list as $k => $l) {
                foreach ($l['data'] as $o => $v) {
                    $detailed = db('detailed')->where('detailed_id', $v['projectId'])->field('warranty_years as warrantYears,warranty_text_1 as warrantyText1,warranty_text_2 as exoneration,display')->find();
                    if (!empty($detailed['warrantYears']) && $detailed['warrantYears'] != '0.00') {
                        $list[$k]['data'][$o]['isWarranty'] = 1;
                        $list[$k]['data'][$o]['warranty']   = ['warrantYears' => $detailed['warrantYears'], 'warrantyText1' => $detailed['warrantyText1'], 'exoneration' => $detailed['exoneration'],];
                    } else {
                        $list[$k]['data'][$o]['warranty']   = null;
                        $list[$k]['data'][$o]['isWarranty'] = 0;
                    }
                    $list[$k]['data'][$o]['artificialTag'] = 0;
                    if (!empty($v['specsList']) && $v['square'] != 0) {
                        $ValueId      = array_column($v['specsList'], 'option_value_id');
                        $CapitalPrice = $common->newCapitalPrice($detailedOptionValue, $v['projectId'], $ValueId);
                        $list[$k]['data'][$o]['forbidden']=0;
                        $list[$k]['data'][$o]['projectMoney'] = $v['projectMoney'];
                        $list[$k]['data'][$o]['allMoney']     = $v['allMoney'];
                        if ($CapitalPrice['code']) {
                           $list[$k]['data'][$o]['forbidden']=1;
                           if (!empty($CapitalPrice['data']['price'])) {
                            $list[$k]['data'][$o]['artificialTag'] = 1;
                        }
                        $CapitalPriceSection = $capital->priceSection($CapitalPrice['data']['price'], $CapitalPrice['data']['artificial'], $CapitalPrice['data']['sum'], $CapitalPrice['data']['sumMast'], $v['square'], $v['company'], null, 0);
                        $list[$k]['data'][$o]['projectMoney'] = $CapitalPriceSection[3];
                        $list[$k]['data'][$o]['allMoney']     = $CapitalPriceSection[1];
                        }
                       
                        
                        foreach ($v['specsList'] as $l1 => $k2) {
                            if ($k2['condition'] == 2) {
                                unset($list[$k]['data'][$o]['specsList'][$l1]);
                                $list[$k]['data'][$o]['specsList'] = array_merge($list[$k]['data'][$o]['specsList']);
                            }
                        }
                    }
                    
                    
                }
                
            }
            foreach ($list as $k => $l) {
                $po               = array_merge($l['data']);
                $list[$k]['data'] = $po;
            }
        }
        
        
        r_date($list, 200);
    }
    
    /*
     * 检查有没有代购
     */
    public function inspect($orderId, $envelopes_id) {
        $envelopesIdFind = db('envelopes')->where('envelopes_id', $envelopes_id)->find();
        if ($envelopesIdFind['type'] == 1) {
            $capitals = (new  capital)->whetherAgency(['ordesr_id' => $orderId, 'types' => 1, 'envelopes_id' => $envelopes_id, 'enable' => 1, 'agency' => 1]);
            if ($capitals > 0) {
                $listOrderType = 1;
            } else {
                $listOrderType = 0;
                (new envelopes)->isUpdate(true)->save(['envelopes_id' => $envelopes_id, 'purchasing_discount' => 0, 'purchasing_expense' => 0]);
            }
            $capitals = (new  capital)->whetherAgency(['ordesr_id' => $orderId, 'types' => 1, 'enable' => 1, 'agency' => 0]);
            if ($capitals == 0) {
                (new envelopes)->isUpdate(true)->save(['envelopes_id' => $envelopes_id, 'expense' => 0, 'give_money' => 0]);
            }
            (new orderModel)->orderAgency(['order_id' => $orderId, 'order_agency' => $listOrderType]);
        }
        
        
    }
    
    /*
     * 预计工时查看
     */
    public function hoursView(Common $common, DetailedOptionValue $detailedOptionValue) {
        
        $data        = Authority::param(['envelopes_id', 'projects']);
        $capitalList = json_decode($data['projects'], true);
        
        $capitalArray = [];
        foreach ($capitalList as $k => $list) {
            if ($list['agency'] == 0) {
                if (isset($list['specsList'])) {
                    $ValueId = array_column($list['specsList'], 'option_value_id');
                } else {
                    $ValueId = [];
                }
                
                
                $sum = $common->newCapitalPrice($detailedOptionValue, $list['projectId'], $ValueId);
                
                if (!$sum['code']) {
                    r_date(null, 300, $sum['msg']);
                }
                $capitalArray['main'][$k]['categoryTitle'] = $sum['data']['categoryTitle'];
                $capitalArray['main'][$k]['work_time']     = $sum['data']['sumTime'] * $list['square'];
                
                if (!empty($sum['data']['work_time'])) {
                    foreach ($sum['data']['work_time'] as $item) {
                        if ($item->begin <= $list['square'] && $item->end > $list['square']) {
                            if ($capitalArray['main'][$k]['work_time'] * $item->value != 0) {
                                $capitalArray['main'][$k]['work_time'] = $capitalArray['main'][$k]['work_time'] * $item->value;
                                
                            }
                            
                        }
                    }
                }
            }
            if ($list['agency'] == 1) {
                $capitalArray['purchasing'][$k]['categoryTitle'] = $list['projectTitle'];
                $detailed                                        = db('detailed')->where('detailed_id', $list['projectId'])->field('detailed.delivery_period_days_1,detailed.delivery_period_days_2')->find();
                $capitalArray['purchasing'][$k]['work_time']     = empty($detailed['delivery_period_days_1']) ? '预计0天' : '预计' . $detailed['delivery_period_days_1'] . '~' . $detailed['delivery_period_days_2'] . '天';
                $capitalArray['purchasing'][$k]['maxTime']       = $detailed['delivery_period_days_2'];
            }
            
            
        }
        
        $main = [];
        if (!empty($capitalArray['main'])) {
            $main = array_unique(array_column($capitalArray['main'], 'categoryTitle'));
        }
        $purchasingList = [];
        $mainList       = [];
        $Sum            = 0;
        
        foreach ($main as $k => $value) {
            $datas = [];
            
            foreach ($capitalArray['main'] as $item) {
                if ($value == $item['categoryTitle']) {
                    $datas[] = $item['work_time'];
                }
                
            }
            $mainList[$k]['title'] = $value;
            $mainList[$k]['data']  = $datas;
            
            $mainList[$k]['sum'] = ceil(array_sum($datas) / 9);
            $Sum                 += $mainList[$k]['sum'];
        }
        $max = [];
        if (!empty($capitalArray['purchasing'])) {
            foreach ($capitalArray['purchasing'] as $y => $item) {
                $purchasingList[$y]['title'] = $item['categoryTitle'];
                $purchasingList[$y]['datas'] = $item['work_time'];
                $purchasingList[$y]['data']  = $item['maxTime'];
                $max[]                       = empty($item['maxTime']) ? 0 : $item['maxTime'];
            }
        }
        
        
        r_date(['main' => ['mainData' => empty($mainList) ? null : array_merge($mainList), 'mainSum' => $Sum], 'purchasing' => ['purchasingData' => empty($purchasingList) ? null : array_merge($purchasingList), 'purchasingListSum' => empty($max) ? 0 : max(array_unique($max))]], 200);
    }
    
    /*
     * 优惠券
     */
    public function coupon(Common $common) {
        
        $data = Authority::param(['orderId']);
        $list = $common->coupon($data['orderId']);
        r_date($list, 200);
        
    }
    
    
    /*
     * 优惠卷重新计算价格
     */
    public function CouponCalculation($envelopes_id, $amount, $agentSum, $types = 0, $capital_id = 0) {
        $envelopesObject = new  Envelopes();
        $envelopes       = $envelopesObject->with(['CapitalList', 'CapitalList.specsList', 'OrderList'])->where(['envelopes_id' => $envelopes_id])->find()->toArray();
        
        $agency      = [];
        $sumlist     = [];
        $capitalsum  = [];
        $datalist    = [];
        $coupon      = null;
        $capitalList = $envelopes['capital_list'];
        
        foreach ($capitalList as $k => $item) {
            if ($item['agency'] == 1) {
                $agency[] = $item;
            }
            if ($item['agency'] == 0) {
                $sumlist[] = $item;
            }
            if ($item['capital_id'] == $capital_id) {
                $capitalsum[] = $item;
            }
        }
        if ($types == 1) {
            if (!empty($capital_id)) {
                $SumCapital = round(array_sum(array_column($capitalsum, 'allMoney')), 2);
                $agencysum  = round(array_sum(array_column($agency, 'allMoney')), 2) - $SumCapital + $agentSum;
                $sumlist    = round(array_sum(array_column($sumlist, 'allMoney')), 2) - $SumCapital + $amount;
            } else {
                $agencysum = round(array_sum(array_column($agency, 'allMoney')), 2) - $agentSum;
                $sumlist   = round(array_sum(array_column($sumlist, 'allMoney')), 2) - $amount;
            }
            
        } else {
            $agencysum = round(array_sum(array_column($agency, 'allMoney')), 2) + $agentSum;
            $sumlist   = round(array_sum(array_column($sumlist, 'allMoney')), 2) + $amount;
        }
        
        if (!empty($envelopes['main_id'])) {
            $coupon = db('coupon_user', config('database.zong'))->join('coupon', 'coupon_user.coupon_id=coupon.id', 'left')->where('coupon_user.id', $envelopes['main_id'])->field('coupon_user.id,coupon.coupon_use_type,coupon.coupon_limit,coupon.coupon_amount,coupon.coupon_type,coupon.coupon_discount,coupon.coupon_prize_title')->find();
        }
        if (!empty($envelopes['purchasing_id'])) {
            $coupon1 = db('coupon_user', config('database.zong'))->join('coupon', 'coupon_user.coupon_id=coupon.id', 'left')->where('coupon_user.id', $envelopes['purchasing_id'])->field('coupon_user.id,coupon.coupon_use_type,coupon.coupon_limit,coupon.coupon_amount,coupon.coupon_type,coupon.coupon_discount,coupon.coupon_prize_title')->find();
        }
        $coupon_user_id            = 0;
        $coupon_discount           = 0;
        $purchasing_discount_money = 0;
        $purchasing_id             = 0;
        
        
        if (!empty($coupon)) {
            if ($coupon['coupon_type'] == 1) {
                if ($sumlist < ($coupon['coupon_limit'] / 100)) {
                    throw new Exception('未达到使用门槛');
                }
                $coupon_discount += ($coupon['coupon_amount'] / 100);
            }
            
        }
        if (!empty($coupon1)) {
            if ($coupon1['coupon_type'] == 2) {
                if ($agencysum < ($coupon1['coupon_limit'] / 100)) {
                    throw new Exception('未达到使用门槛');
                }
                $purchasing_discount_money += $agencysum * (1 - ($coupon1['coupon_discount'] / 100));
            }
            
        }
        if ($coupon_discount != 0) {
            $datalist['main_discount_money'] = $coupon_discount;
            $datalist['give_money']          = $envelopes['give_money'] - $envelopes['main_discount_money'] + $coupon_discount;
            
        }
        if ($purchasing_discount_money != 0) {
            
            $datalist['purchasing_discount_money'] = $purchasing_discount_money;
            $datalist['purchasing_discount']       = $envelopes['purchasing_discount'] - $envelopes['purchasing_discount_money'] + $purchasing_discount_money;
            
        }
        if ($coupon['coupon_type'] != 3) {
            if (!empty($coupon1) && !empty($datalist)) {
                \db('envelopes')->where('envelopes_id', $envelopes_id)->update($datalist);
            }
            if (!empty($coupon) && !empty($datalist)) {
                \db('envelopes')->where('envelopes_id', $envelopes_id)->update($datalist);
            }
            
        }
        
        
    }
    
    /*
      * 手动推送审批增减项
      */
    public function Manual(Approval $approval, Capital $capital) {
        $data        = Authority::param(['capital_id', 'quantity', 'order_id']);
        $capitalFind = $capital->QueryOne($data['capital_id']);
        $user        = Db::table('order')->join('user', 'user.user_id=order.assignor', 'left')->where('order.order_id', $data['order_id'])->find();
        if (isset($data['quantity']) && $data['quantity'] != 0) {
            $title        = $capitalFind['class_b'] . '减少方量到(' . $data['quantity'] . ')';
            $signed       = 1;
            $approvalType = 9;
        } else {
            $title        = $capitalFind['class_b'] . '项目减项(' . $user['username'] . ')';
            $signed       = $capitalFind['signed'];
            $approvalType = 6;
        }
        $approval->Reimbursement($data['capital_id'], $title, $user['username'], $approvalType);
    }
    
    /*
      * 手动推送审批报销
      */
    public function ManualList(Approval $approval, Capital $capital, MaterialScience $materialScience) {
        
        $data          = Authority::param(['id', 'order_id']);
        $user          = Db::table('order')->join('user', 'user.user_id=order.assignor', 'left')->where('order.order_id', $data['order_id'])->find();
        $reimbursement = db('reimbursement')->where(['id' => $data['id']])->find();
        $title         = array_search($reimbursement['classification'], array_column($materialScience->list_reimbursement_type(2), 'type'));
        if ($reimbursement['type'] == 1) {
            $title = $user['username'] . $materialScience->list_reimbursement_type(2)[$title]['name'] . '报销';
        } else {
            $app_user = Db::connect(config('database.db2'))->table('app_user')->where('id', $reimbursement['user_id'])->value('username');
            $title    = '师傅' . $app_user . $materialScience->list_reimbursement_type(2)[$title]['name'] . '报销';
        }
        $approval->Reimbursement($data['id'], $title, $user['username'], $reimbursement['classification']);
        
    }
    
    /*
     * 确认甘特图
     */
    public function ConfirmGanttChart($ganttChart, $envelopes_id, $order_id, $type) {
        if (!empty($ganttChart)) {
            db('envelopes_gantt_chart')->where('order_id', $order_id)->where('envelopes_id', $envelopes_id)->update(['delete_time' => time()]);
            db('envelopes_gantt_chart')->insert(['envelopes_id' => $envelopes_id, 'order_id' => $order_id, 'picture' => '', 'created_time' => time(), 'result' => json_encode($ganttChart), 'duration' => $ganttChart['weekday'], 'type' => $type]);
        }
    }
     /*
     * 管理费
     */
    
    public function guanlifei($order_setting, $ordesr_id, $envelopes, $type = 1) {
        
        $envelopesIDtype = db('envelopes')->where('envelopes_id', $envelopes)->find();
        if ($envelopesIDtype['type'] == 1) {
            $capital = db('capital')->where('types', 1)->where('enable', 1)->where('ordesr_id', $ordesr_id)->where('envelopes_id', $envelopes)->select();
        } else {
            $capital = db('capital')->where('types', 1)->where('ordesr_id', $ordesr_id)->where('envelopes_id', $envelopes)->select();
        }
        $man = 0;
        $pr  = 0;
        foreach ($capital as $l) {
            if ($l['products'] == 1 && $l['products_v2_spec'] != 0 && $l['is_product_choose'] == 1 && $l['agency'] == 0) {
                $man += $l['to_price'];
            }
            if ($l['agency'] == 0 && $l['products'] == 0) {
                $man += $l['to_price'];
            }
            if ($l['products'] == 1 && $l['products_v2_spec'] == 0 && $l['agency'] == 0) {
                $man += $l['to_price'];
            }
            
            if ($l['products'] == 1 && $l['products_v2_spec'] != 0 && $l['is_product_choose'] == 1 && $l['agency'] == 1) {
                $pr += $l['to_price'];
            }
            if ($l['agency'] == 1 && $l['products'] == 0) {
                $pr += $l['to_price'];
            }
            if ($l['products'] == 1 && $l['products_v2_spec'] == 0 && $l['agency'] == 1) {
                $pr += $l['to_price'];
            }
        }
        
        if ($man != 0) {
            $alone1 = round($man * ($order_setting['max_expense_rate'] / 100), 2);
            Db::connect(config('database.zong'))->table('log')->insertGetId(['admin_id' => $this->us['user_id'], 'created_at' => time(), 'content' => $alone1, 'type' => 88, 'msg' => '重新计算主材管理费', 'ord_id' => $ordesr_id]);
            db('envelopes')->where(['envelopes_id' => $envelopes])->update(['expense' => $alone1]);
        } else {
            db('envelopes')->where(['envelopes_id' => $envelopes])->update(['expense' => 0]);
        }
        if ($pr != 0) {
            $alone2 = round($pr * ($order_setting['max_agent_expense_rate'] / 100), 2);
            Db::connect(config('database.zong'))->table('log')->insertGetId(['admin_id' => $this->us['user_id'], 'created_at' => time(), 'content' => $alone2, 'type' => 88, 'msg' => '重新计算代购主材管理费', 'ord_id' => $ordesr_id]);
            db('envelopes')->where(['envelopes_id' => $envelopes])->update(['purchasing_expense' => $alone2]);
        } else {
            db('envelopes')->where(['envelopes_id' => $envelopes])->update(['purchasing_expense' => 0]);
        }
        if ($type == 3) {
            $capitalProfit = (new capital)->capitalProfit($ordesr_id, 0, $envelopes);
            
        }
        if ($type == 2) {
            $capitalProfit = (new capital)->capitalProfit($ordesr_id, 0, $envelopes);
            if ((string)round(($capitalProfit['give_money'] + $capitalProfit['purchasing_discount']) / ($capitalProfit['MainMaterialMoney'] + $capitalProfit['agencyMoney']), 2) * 100 > $order_setting['max_discount_rate']) {
                if ($capitalProfit['give_money'] != 0) {
                    $capitalGiveMain = (new capital)->where(['ordesr_id' => $ordesr_id, 'types' => 1, 'envelopes_id' => $envelopes, 'give' => 2, 'agency' => 0])->sum('give_to_money');
                    $alonediscount   = round($capitalProfit['MainMaterialMoney'] * ($order_setting['max_discount_rate'] / 100), 2);
                    db('envelopes')->where(['envelopes_id' => $envelopes])->update(['give_money' => $alonediscount + $capitalGiveMain + $capitalProfit['products_main_discount_money'],//优惠金额
                    
                    ]);
                }
                if ($capitalProfit['purchasing_discount'] != 0) {
                    $capitalGive    = (new capital)->where(['ordesr_id' => $ordesr_id, 'types' => 1, 'envelopes_id' => $envelopes, 'give' => 2, 'agency' => 1])->sum('give_to_money');
                    $alone2discount = round($capitalProfit['agencyMoney'] * ($order_setting['max_discount_rate'] / 100), 2);
                    db('envelopes')->where(['envelopes_id' => $envelopes])->update(['purchasing_discount' => $alone2discount + $capitalGive + $capitalProfit['products_purchasing_discount_money'],//优惠金额
                    ]);
                }
            }
        }
        
    }
    
    
    
    /*
     * 查看审批详情
     */
    public function viewApprovalDetails() {
        $data            = Authority::param(['order_id', 'envelopesId']);
        $approval_record = \db('approval_record', config('database.zong'))->field('bi_user.username,FROM_UNIXTIME(approval_record.created_time,"%Y-%m-%d %H:%i:%s") as createdTime,approval_info.reject_desc as rejectDesc,approval_info.approval_status as status')->join('approval', 'approval.relation_id=approval_record.id and approval.type=13', 'left')->join('approval_info', 'approval.approval_id=approval_info.approval_id', 'left')->join('bi_user', 'bi_user.user_id=approval.nxt_id', 'left')->where(['approval_record.order_id' => $data['order_id'], 'approval_record.relation_id' => $data['envelopesId'], 'approval_record.type' => 10])->where('approval.city_id', config('cityId'))->order('approval_record.id desc')->find();
        r_date($approval_record, 200);
    }
    
    /*
   * 重新提交审批
   */
    public function resubmitForApproval(Approval $approval) {
        $data = Authority::param(['order_id', 'envelopesId', 'approvalPeriod', 'approvalRemark']);
        db()->startTrans();
        try {
            $approval_record = db('approval_record', config('database.zong'))->where(['relation_id' => $data['envelopesId'], 'city_id' => config('cityId'), 'order_id' => $data['order_id'], 'type' => 10])->where('status', 0)->order('id desc')->column('id');
            if ($approval_record) {
                db('approval', config('database.zong'))->where('type', 13)->where('city_id', config('cityId'))->where('order_id', $data['order_id'])->whereIn('relation_id', $approval_record)->update(['status' => 1]);
                db('approval_schedule', config('database.zong'))->whereIn('relation_id', $approval_record)->update(['approval_status' => 2, 'remarks' => '申请人撤销审批']);
                db('approval_bef', config('database.zong'))->where('type', 13)->where('city_id', config('cityId'))->whereIn('approval_id', $approval_record)->where('state', 0)->update(['state' => 1]);
                db('approval_info', config('database.zong'))->where('type', 13)->where('city_id', config('cityId'))->whereIn('relation_id', $approval_record)->update(['approval_status' => 2, 'reject_desc' => '申请人撤销审批']);
                db('approval_record', config('database.zong'))->whereIn('id', $approval_record)->update(['status' => 2, 'explains' => '申请人撤销审批']);
            }
            $gong     = db('envelopes')->where('envelopes_id', $data['envelopesId'])->value('gong');
            $duration = db('envelopes_gantt_chart')->where('envelopes_id', $data['envelopesId'])->where('delete_time', 0)->value('duration');
            if ($data['approvalPeriod'] > $gong) {
                $description = \db('approval_record', config('database.zong'))->insertGetId(['city_id' => config('cityId'), 'order_id' => $data['order_id'], 'relation_id' => $data['envelopesId'], 'type' => 10, 'change_value' => $data['approvalPeriod'] - $duration, 'status' => 0, 'created_time' => time(), 'explains' => $data['approvalRemark'], 'picture' => '',]);
                $approval->Reimbursement($description, '店长' . $this->us['username'] . '超工期申请', $this->us['username'], 13);
            } else {
                db('envelopes')->where('envelopes_id', $data['envelopesId'])->update(['gong' => $data['approvalPeriod']]);
            }
            db()->commit();
            r_date(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            r_date(null, 300, $e->getMessage());
        }
    }
    
    
    /*
     * 工艺说明
     */
    public function Processdescription(Detailed $Detailed) {
        
        $data = Authority::param(['id', 'optionId']);
        $op   = json_decode($data['optionId'], true);
        
        $list                 = $Detailed->with(['detailedListValue'])->where('detailed_id', $data['id'])->find();
        $option_value_title   = [];
        $craft                = [];
        $material             = [];
        $listData['bigTitle'] = $list['detailed_title'];
        $detailed_list_value  = $list['detailed_list_value'];
        foreach ($list['detailed_list_value'] as $list) {
            foreach ($op as $o) {
                if ($list['option_value_id'] == $o) {
                    if (!empty($list['option_value_title'])) {
                        $option_value_title[] = $list;
                    }
                    if (!empty($list['craft'])) {
                        $craft[] = $list;
                    }
                    if (!empty($list['material'])) {
                        $material[] = $list;
                    }
                }
                
            }
            
        }
        $listData['title']    = implode(array_column($option_value_title, 'option_value_title'), '/');
        $listData['craft']    = empty(array_column($craft, 'craft')) ? null : array_column($craft, 'craft');
        $listData['material'] = empty(array_column($material, 'craft')) ? null : array_column($material, 'material');
        r_date($listData, 200);
    }
    
    /*
     * 施工中编辑质保
     */
    
    public function constructionQualityAssurance() {
        $data = Authority::param(['projectList']);
        $op   = json_decode($data['projectList'], true);
        foreach ($op as $item) {
            foreach ($item['data'] as $l) {
                $detailedList   = Db::table('detailed')->where('detailed_id', $l['projectId'])->find();
                $zhi            = 0;
                $warranty_years = 0;
                if ($l['isWarranty'] == 1) {
                    $warranty_years = $detailedList['warranty_years'];
                    $zhi            = 1;
                }
                
                \db('capital')->where('capital_id', $l['capital_id'])->update(['zhi' => $zhi, 'warranty_years' => $warranty_years, 'warranty_reason' => isset($l['warrantyReason']) ? $l['warrantyReason'] : '']);
            }
            
        }
        r_date(null, 200);
    }
    
    private function auxiliaryInteractiveInsert($id, $order_id, $v) {
        
        if (!empty($id)) {
            //交付标准
            if (isset($v['product_id']) && !empty($v['product_id']) && $v['agency'] != 1) {
                $standardId = db('auxiliary_interactive')->where('auxiliary_interactive.detailed_id', $v['product_id'])->where('auxiliary_interactive.pro_types', 0)->where('auxiliary_interactive.parents_id', 0)->column('auxiliary_interactive.id');
                if (!empty($standardId)) {
                    $allId = db('auxiliary_project_list')->where(['capital_id' => $id, 'order_id' => $order_id])->column('id');
                    db('auxiliary_project_list')->where(['capital_id' => $id, 'order_id' => $order_id])->update(['delete_time' => time()]);
                    if (!empty($allId)) {
                        db('auxiliary_delivery_schedule')->whereIn('auxiliary_project_list_id', $allId)->update(['delete_time' => time()]);
                    }
                    foreach ($standardId as $item) {
                        $auxiliary_interactive  = db('auxiliary_interactive')->where('pro_types', 0)->where('parents_id', $item)->column('id');
                        $auxiliary_project_list = db('auxiliary_project_list')->insertGetId(['auxiliary_id' => $item, 'capital_id' => $id, 'order_id' => $order_id, 'created_time' => time()]);
                        foreach ($auxiliary_interactive as $datum) {
                            if (!empty($datum)) {
                                 db('auxiliary_delivery_schedule')->insertGetId(['auxiliary_interactive_id' => $datum, 'auxiliary_project_list_id' => $auxiliary_project_list,'work_process_accept_std_ai_acpt_std'=>'']);
                            }
                        }
                    }
                }
            }
        }
    }
    
    /*
     * 获取分组信息
     */
    public function categoryName() {
        $data         = Authority::param(['envelopesId']);
        $envelopes_id = $data['envelopesId'];
        $categoryName = db('capital')->where('envelopes_id', $envelopes_id)->where('products', 0)->where('types', 1)->where('agency', 0)->where('enable', 1)->column('categoryName');
        $categoryName = array_merge($categoryName, ["代购主材"]);
        r_date(array_merge(array_unique($categoryName)), 200);
    }
    
    /**
     * 获取费用已选列表
     */
    public function list(DetailedCategory $detailedCategory) {
        $data         = Authority::param(['group', 'type']);
        $request              = Request::instance()->get();
        $group        = $data['group'];
        //首页的“基装清单”区分大改只展示店长对应业务的清单
         if($this->us['in_business']==2 && isset($request['isBasicEquipment']) && $request['isBasicEquipment']==1){
            $group        = 4;
        }
         if($this->us['in_business']==3 && isset($request['isBasicEquipment']) && $request['isBasicEquipment']==1){
            $group        = 5;
        }
        $detailedList = $detailedCategory->where('detailed_category.is_enable', 1);
        if ($data['type'] == 0) {
            $detailedList->where('is_agency', 0)->where('pid', 0)->with(['detailedList' => function ($query) use ($group) {
                $query->where('detailed.groupss', $group)->with('detailedListValue');
            }]);
        } else {
            $detailedList->where('is_agency', 1)->where('id', '<>', 22)->with(['detailedListAnge','detailedListAnge.detailedListValue']);
        }
        
        $detailedLists = $detailedList->order('detailed_category.sort desc')->select();
        if($data['type'] == 0){
            foreach ($detailedLists as $k => $ite) {
                if (!empty($ite['detailed_list'])) {
                    foreach ($ite['detailed_list'] as $l => $value) {
                        $value['title']      = $ite['title'];
                        $value['isWarranty'] = 1;
                        if (!empty($value['warrantYears']) && $value['warrantYears'] != '0.00') {
                            $value['warranty'] = ['warrantYears' => $value['warrantYears'], 'warrantyText1' => $value['warrantyText1'], 'exoneration' => $value['exoneration'],];
                        } else {
                            $value['warranty']   = null;
                            $value['isWarranty'] = 0;
                        }
                        
                        $value['types']    = 4;
                        $value['group']    = $value['groupss'];
                        $detailedListValue = $value->detailed_list_value;
                        $desc_attachment =array_column($detailedListValue, 'desc_attachment');
                        $non_empty_array = array_filter($desc_attachment, function($value) {
                            return !is_null($value) && $value !== '';
                        });
                        $value['desc_attachment']  =!empty($non_empty_array)?1:0;
                        if (!empty(array_column($detailedListValue, 'option_value_title'))) {
                            $value['detailedListValues'] = $value['detailed_title'] . ',' . implode(array_column($detailedListValue, 'option_value_title'), ',');
                            
                        } else {
                            $value['detailedListValues'] = $value['detailed_title'];
                        }
                        unset($value->detailedListValue,$value->detailed_list_value, $value['warrantYears'], $value['warrantyText1'], $value['exoneration'], $value['groupss']);
                    }
                    
                }
                
                if ($ite['id'] == 0) {
                    $detailedLists[$k]['detailed_list'] = isset($detailedListList) ? $detailedListList : [];
                }
                
                unset($detailedLists[$k]['sort'], $detailedLists[$k]['is_enable'], $detailedLists[$k]['created_at'], $detailedLists[$k]['updated_at'], $detailedLists[$k]['type'], $detailedLists[$k]['is_agency'], $detailedLists[$k]['condition']);
            }
        }else{
            $pidList = [];
            foreach ($detailedLists as $k => $l) {
                $l['type']=1;
                if ($l['pid'] != 0) {
                    $pidList[] = $l;
                }
                
            }
          
            foreach ($detailedLists as $k => $o) {
                $dataList = [];
                foreach ($pidList as $m => $l) {
                    if ($o['id'] == $l['pid']) {
                        $l['detailed_title']     = $l['title'];
                        $l['detailedListValues'] = '';
                        $l['types']              = 4;
                        $detailed_list_ange      = $l['detailed_list_ange'];
                        unset($pidList[$m]['detailed_list_ange']);
                        foreach ($detailed_list_ange as $b => $value) {
                            $value['type']      =1;
                            $value['isWarranty'] = 1;
                            if (!empty($value['warrantYears']) && $value['warrantYears'] != '0.00') {
                                $value['warranty'] = ['warrantYears' => $value['warrantYears'], 'warrantyText1' => $value['warrantyText1'], 'exoneration' => $value['exoneration'],];
                            } else {
                                $value['warranty']   = null;
                                $value['isWarranty'] = 0;
                            }
                            $value['types']    = 4;
                            $value['group']    = $value['groupss'];
                            
                            $detailedListValue = $value->detailed_list_value;
                            $desc_attachment =array_column($detailedListValue, 'desc_attachment');
                            $non_empty_array = array_filter($desc_attachment, function($value) {
                                return !is_null($value) && $value !== '';
                            });
                            $value['desc_attachment']  =!empty($non_empty_array)?1:0;
                            if (!empty(array_column($detailedListValue, 'option_value_title'))) {
                                $value['detailedListValues'] = $value['detailed_title'] . ',' . implode(array_column($detailedListValue, 'option_value_title'), ',');
                                
                            } else {
                                $value['detailedListValues'] = $value['detailed_title'];
                            }
                            unset($value->detailedListValue, $value->detailed_list_value,$value['warrantYears'], $value['warrantyText1'], $value['exoneration'], $value['groupss']);
                            $value['square']      =0;
                            $value['title']      = $l['title'];
                            
                        }
                        if (!empty($detailed_list_ange) &&  $l['title'] !="零采") {
                            $l['detailed_list_ange'] = array_merge($detailed_list_ange);
                            $dataList[]              = $l;
                        }
                    }
                }
                if (empty($dataList)) {
                    unset($detailedLists[$k]);
                } else {
                    $detailedLists[$k]['detailed_list'] = $dataList;
                }
                unset($detailedLists[$k]['detailed_list_ange']);
            }
            $detailedLists = array_merge($detailedLists);
     }
      
        r_date($detailedLists, 200, '操作成功');
        
    }
    
    
    /**
     * 获材工资料用已选列表
     */
    public function info(DetailedOption $detailedOption) {
        $data                   = Authority::param(['id']);
        $getOptionValue['list'] = $detailedOption->with(['detailedListOptionValues' => function ($query) use ($data) {
            $query->where('detailed_option_value.detailed_id', $data['id'])->group('detailed_option_value.option_value_id');
        }])->where('condition', '<>', 2)->order('option_id desc')->select();
        $detailed_option_sort   = db('detailed_option_sort', config('database.zong'))->where('detailed_id', $data['id'])->select();
        
        foreach ($getOptionValue['list'] as $k => $value) {
            if ($detailed_option_sort) {
                foreach ($detailed_option_sort as $item) {
                    if ($item['option_id'] == $value['option_id']) {
                        $value['sort'] = $item['sort'];
                    }
                    
                }
                
            }
            if (!empty($value['detailed_list_option_values'])) {
                $value['sort']           = isset($value['sort']) ? $value['sort'] : 0;
                foreach ($value['detailed_list_option_values'] as $key=>$val){
                    $val['desc_tag']           = empty($val['desc_tag']) ?null : json_decode($val['desc_tag'],true);
                    $title  = empty($val['desc_text']) ?null : json_decode($val['desc_text'],true);
                    $val['desc_text'] ='';
                    if(!empty($title)){
                        foreach ($title as $v){
                            $content[]=$v['title'].':'.$v['value'].'。';
                        }
                        $val['desc_text']=implode($content,"<br/>");
                    }
                    $desc_attachment=empty($val['desc_attachment']) ?null: json_decode($val['desc_attachment'],true);
                    $val['desc_attachment']           ='';
                    if(!empty($desc_attachment)){
                        $val['desc_attachment']           =$desc_attachment[0];
                    }
                    
                }
                $getOptionList['list'][] = $value;
            }
        }
        if (isset($getOptionList['list'])) {
            $getOptionList['list'] = (new Visa())->arraySort($getOptionList['list'], 'sort', SORT_ASC);
        }
        $detailed                 = db('detailed')->join('unit', 'unit.id=detailed.un_id')->where('detailed_id', $data['id'])->field('rmakes,unit.title,artificial')->find();
        $getOptionList['remarks'] = $detailed['rmakes'];
        $getOptionList['title']   = $detailed['title'];
        $getOptionList['artificial']   = $detailed['artificial'];
        
        r_date($getOptionList, 200, '操作成功');
    }
    
    /**
     * 计算单价
     */
    public function getListValuation(DetailedOptionValue $detailedOptionValue, Common $common, Capital $capital) {
        $data = Authority::param(['data', 'id', 'types', 'capital_id']);
        if ($data['types'] == 4 || $data['types'] == 1) {
            $detailedValue = $common->newCapitalPrice($detailedOptionValue, $data['id'], json_decode($data['data'], true));
            if (!$detailedValue['code']) {
                r_date([], 300, $detailedValue['msg']);
            }
            $detailedValueList = $detailedValue['data'];
        } else {
            if ($data['types'] == 0) {
                $product_chan               = db('product_chan')->where('product_id', $data['id'])->find();
                $detailedValueList['sum']   = $product_chan['prices'];
                $detailedValueList['price'] = $product_chan['price_rules'];
                $detailedValueList['unit']  = $product_chan['price_rules'];
                
            } elseif ($data['types'] == 2) {
                $capitalIdFind              = $capital->QueryOne($data['capital_id']);
                $detailedValueList['sum']   = $capitalIdFind['un_Price'];
                $detailedValueList['price'] = [];
                $detailedValueList['unit']  = $capitalIdFind['company'];
                
            }
        }
        r_date(['price' => $detailedValueList['sumMast'], 'artificial' => $detailedValueList['artificial'], 'unTitle' => $detailedValueList['unit']], 200);
        
    }
    
    
  /*
     * 手动添加施工节点
     */
    public function auxiliaryInteractive($capitalId,$orderId) {
        $capitalList = db('capital')->whereIn('capital_id',$capitalId)->select();
            
            foreach ($capitalList as $ke => $list) {
                $list['product_id'] = $list['projectId'];
                self::auxiliaryInteractiveInsert($list['capital_id'], $orderId, $list);
            }
        
    }
    
    /*
     * 报价核检
     */
    public function inspection(Common $common, Capital $capital, DetailedOptionValue $detailedOptionValue, Envelopes $envelopes) {
//        $data              = Authority::param(['orderId', 'company', 'give_money', 'purchasing_discount', 'project_title', 'productJson', 'couponId', 'only', 'expense', 'purchasing_expense']);
        $data              = Request::instance()->post();
        $this->us['city']  = config('cityId');
        $user              = $this->us;
        $orderId           = isset($data['orderId']) ? $data['orderId'] : $data['order_id'];
        $envelopes_id      = isset($data['envelopesId']) ? $data['envelopesId'] : 0;
        $order_setting     = db('order_setting')->where('order_id', $orderId)->find();
        $u8c_invprice      = db('u8c_virtual_material', config('database.zong'))->where(function ($query) use ($user) {
            $query->where('store_id', $user['store_id'])->whereOr(function ($query) use ($user) {
                $query->where('city_id', $user['city'])->where('store_id', 0);
            });
        })->select();
        $labor_cost_config = db('labor_cost_config', config('database.zong'))->where('city_id', config('cityId'))->find();
        $state             = db('order')->where('order_id', $orderId)->find();
        if (((isset($data['company']) && !empty($data['company'])) || (isset($data['productJson']) && !empty($data['productJson']))) && $state['state'] < 4) {
            $companyJson = empty($data['company']) ? [] : json_decode($data['company'], true);//清单
            $productJson = empty($data['productJson']) ? [] : json_decode($data['productJson'], true);//套餐
            $productIds  = isset($data['only']) ? $data['only'] : [];//质保卡
            $couponId    = isset($data['couponId']) ? $data['couponId'] : [];//优惠券
            
            $ValidateCollection = $envelopes->inspection($companyJson, $productJson, $orderId, $common, $capital, $detailedOptionValue, $data['give_money'], $data['purchasing_discount'], $couponId, $productIds, $this->us['user_id'], $order_setting, $data['project_title'], $data['expense'], $data['purchasing_expense']);
            if ($ValidateCollection['code']==300) {
                r_date([], 300, $ValidateCollection['msg']);
            }
            $l = $ValidateCollection['capitalList'];
        } else {
            $l = $capital->capitalCheck($data['orderId'], $envelopes_id);
        }
        $result=[];
        foreach ($l as $k => $v) {
            $zhuMaterialCost = 0;
            $zhuProfitMargin = 0;
            if ($v['material_ratio'] > 0 && $v['agency'] == 0) {
                $zhuMaterialCost += $v['main_price'] * ($v['material_ratio'] / 100);
            } else {
                if (!empty($v['content'])) {
                    $content = json_decode($v['content'], true);
                    foreach ($content as $k => $item) {
                        foreach ($u8c_invprice as $value) {
                            
                            if ($item['invcode'] == $value['invcode'] && $item['sum'] == 0 && $value['profit_margin'] == '0.00') {
                                $content[$k]['sum'] = bcmul(bcmul($item['recommended_quantity'], $value['nabprice'], 2), $v['square'], 2);
                                $zhuMaterialCost    += $content[$k]['sum'];
                                
                            }
                            if ($item['invcode'] == $value['invcode'] && $value['profit_margin'] > 0) {
                                $zhuProfitMargin += bcmul($v['main_price'], ($value['profit_margin'] / 100), 4);
                            }
                        }
                        
                    }
                    $v['content'] = json_encode($content);
                }
            }
            
            unset($v['capital_id']);
            $v['zhuMaterialCost'] = $zhuMaterialCost + $zhuProfitMargin;
            $v['zhuProfitMargin'] = $zhuProfitMargin;
            $v['daiOrderFee']     = 0;
            $v['zhuOrderFee']     = 0;
            if ($v['main_price'] == 0 && $v['agent_price'] != 0) {
                $v['daiOrderFee'] = $v['order_fee'];
                $v['zhuOrderFee'] = 0;
            }
            $result[$v['envelopes_id']][] = $v;
        }
        $tageList=[];
        foreach ($result as $k => $list) {
            $schemeTag['envelopes_id'] = $k;
            $schemeTag['type']         = $result[$k][0]['type'];
            $schemeTag['createdTime']  = date('Y-m-d H:i:s', $result[$k][0]['created_time']);
            $schemeTag['title']        = $result[$k][0]['project_title'];
            $notes                     = '';
//            foreach ($list as $p=>$v){
//                if($v['agent_price']*0.6 >$v['daiMaterialCost']){
//                    $list[$p]['daiMaterialCost']=(string)round($v['agent_price']*0.6);
//                    $notes='因主材成本未配置，当前计算代购合同利润为系统推算';
//                }
//            }
            $zhu           = array_sum(array_column($list, 'main_price')) - $result[$k][0]['give_money'] + $result[$k][0]['expense'];//祝主合同清单
            $zhuLaborCosts = array_sum(array_column($list, 'zhuLaborCost'));
            $zhuLaborCost  = $zhuLaborCosts + $zhu * ($labor_cost_config['fixed_labor_cost_ratio'] / 100);//人工费
            $zhuMeasurefee = bcmul($zhu, ($labor_cost_config['main_contract_measure_ratio'] / 100), 2);//措施费
            
            $zhuMaterialCost = array_sum(array_column($list, 'zhuMaterialCost'));//材料费
            // $zhuOrderFee     = $result[$k][0]['order_fee'];//订单费
            $zhuOrderFee=0;
            $zhuProfit1=0;
            $zhuProfit       = 0;
            if ($zhu != 0) {
                $zhuProfit1 = bcsub(bcsub(bcsub(bcsub($zhu, $zhuLaborCosts, 4), $zhuMeasurefee, 4), $zhuMaterialCost, 4), $zhuOrderFee, 4);
                $zhuProfit = bcsub(bcmul(sprintf('%.4f', $zhuProfit1 / $zhu), 100, 4), $labor_cost_config['fixed_labor_cost_ratio'], 3);//利润
            }
            $dai             = array_sum(array_column($list, 'agent_price')) - $result[$k][0]['purchasing_discount'] + $result[$k][0]['purchasing_expense'];
            $daiMeasurefee   = bcmul($dai, ($labor_cost_config['agency_contract_measure_ratio'] / 100), 2);
            $daiLaborCost    = array_sum(array_column($list, 'daiLaborCost'));
            // $daiOrderFee     = $result[$k][0]['order_fee'];
            $daiOrderFee=0;
            $daiMaterialCost = array_sum(array_column($list, 'daiMaterialCost'));//材料费
            
            if ($zhu != 0) {
                $daiOrderFee = 0;
            }
            $daiProfit = 0;
            $daiProfit1=0;
            
            if ($dai != 0) {
                $estimate = $daiLaborCost + $daiMaterialCost;
                if ($estimate == 0) {
                    $notes           = '因主材成本未配置，当前计算代购合同利润为系统推算';
                    $daiMaterialCost = array_sum(array_column($list, 'agent_price')) * 0.6;
                    $daiMeasurefee   = 0;
                }
                $daiProfit1 = bcsub(bcsub(bcsub(bcsub($dai, $daiLaborCost, 4), $daiMeasurefee, 4), $daiMaterialCost, 4), $daiOrderFee, 4);
                $daiProfit = bcmul(sprintf('%.4f', $daiProfit1 / $dai), 100, 4);//利润
            }
            $schemeTag['list'] = [['title' => '人工成本', 'money' => bcadd($zhuLaborCost, $daiLaborCost, 2), 'color' => '#20A970', 'profit' => (string)(round((bcadd($zhuLaborCost, $daiLaborCost, 2) / bcadd($zhu, $dai, 2)), 4) * 100),], ['title' => '材料成本', 'money' => bcadd($zhuMaterialCost, $daiMaterialCost, 2), 'color' => '#6494FF', 'profit' => (string)(round((bcadd($zhuMaterialCost, $daiMaterialCost, 2) / bcadd($zhu, $dai, 2)), 4) * 100),], ['title' => '措施费《预计》', 'money' => bcadd($zhuMeasurefee, $daiMeasurefee, 2), 'color' => '#FFB195', 'profit' => (bcadd($labor_cost_config['agency_contract_measure_ratio'], $labor_cost_config['main_contract_measure_ratio'])),],
                
                // ['title' => '订单成本', 'money' => $result[$k][0]['order_fee'], 'color' => '#8F78FF', 'profit' => (string)(round(($result[$k][0]['order_fee'] / bcadd($zhu, $dai, 2)), 4) * 100),]
            ];
            $schemeTag['data'] = [['title' => '人工', 'color' => '#20A970', 'profit' => (string)(round((bcadd($zhuLaborCosts, $daiLaborCost, 2) / bcadd($zhu, $dai, 2)), 4) * 100),], ['title' => '材料', 'color' => '#6494FF', 'profit' => (string)(round((bcadd($zhuMaterialCost, $daiMaterialCost, 2) / bcadd($zhu, $dai, 2)), 4) * 100),], ['title' => '措施费', 'color' => '#FFB195', 'profit' => (bcadd($labor_cost_config['agency_contract_measure_ratio'], $labor_cost_config['main_contract_measure_ratio'])),],
                
                // ['title' => '成本', 'color' => '#8F78FF', 'profit' => (string)(round(($result[$k][0]['order_fee'] / bcadd($zhu, $dai, 2)), 4) * 100),]
            ];
            
            $schemeTag['zhu']       = (string)$zhu;//利润
            $schemeTag['zhuProfit'] = $zhuProfit;//利润
            $schemeTag['dai']       = $dai;//利润
            $schemeTag['daiProfit'] = $daiProfit;
            $schemeTag['notes']     = $notes;
            // $schemeTag['profit']    =(string)(round( (bcadd(bcsub($zhuProfit1,(bcmul($zhu,($labor_cost_config['fixed_labor_cost_ratio']/100),3)),3),$daiProfit1,3)/bcadd($zhu, $dai, 3)),5)* 100);
            $schemeTag['profit']    =bcadd($zhuProfit,$daiProfit,3);
            $schemeTag['sumMoney']  = bcadd($dai, $zhu, 3);
//            $schemeTag['data'] = $result[$k];
            $tageList[] = $schemeTag;
        }
        r_date($tageList, 200);
    }
    
    /*
     * 快速报价埋点
     */
    public function quickBurialPoint() {
        $data                 = Authority::param(['eventName', 'pageTitle', 'orderId']);
        $order                = db('order')->where('order_id', $data['orderId'])->find();
        $detailed_option_sort = db('shopwner_quick_quotation', config('database.statistics'))->insert(['user_id' => $this->us['user_id'], 'username' => $this->us['username'], 'time' => time(), 'event_name' => $data['eventName'], 'page_title' => $data['pageTitle'], 'order_state' => $order['state'], 'order_id' => $data['orderId'], 'ip' => $_SERVER['REMOTE_ADDR'], 'type' => 1,]);
        r_date(null, 200);
    }
    
    /*
   * 甘特图
   */
    public function estimatedConstructionPeriod(DetailedWorkProcess $detailedWorkProcess, Capital $capital, Common $common) {
        $data         = Request::instance()->post();
        $orderId      = isset($data['orderId']) ? $data['orderId'] : $data['orderId'];
        $envelopes_id = isset($data['envelopesId']) ? $data['envelopesId'] : 0;
        $subordinate  = isset($data['subordinate']) ? $data['subordinate'] : 0;
        $state        = db('order')->where('order_id', $orderId)->find();
        if ($data['type'] != 3) {
            $companyJson  = empty($data['company']) ? [] : json_decode($data['company'], true);//清单
            $productJson  = empty($data['productJson']) ? [] : json_decode($data['productJson'], true);//套餐
            $companyLists = [];
            $productList  = [];
            if ($companyJson) {
                if (!empty($companyJson)) {
                    foreach ($companyJson as $ke => $value) {
                        $values['categoryName'] = $value['categoryName'];
                        $values['fang']         = $value['fang'];
                        $values['projectTitle'] = $value['projectTitle'];
                        $values['unit']         = $value['unit'];
                        $values['product_id']   = $value['product_id'];
                        $values['agency']       = $value['agency'];
                        $companyLists[]         = $values;
                    }
                    
                }
            }
            if (!empty($productJson)) {
                foreach ($productJson as $item) {
                    if (!empty($item['list'])) {
                        foreach ($item['list'] as $k => $v) {
                            if (!empty($v['data'])) {
                                foreach ($v['data'] as $ke => $value) {
                                    if ($value['required'] == 1 || ($value['required'] == 2 && $value['isProductChoose'])) {
                                        $values['categoryName'] = $item['title'];
                                        $values['fang']         = $value['square'];
                                        $values['unit']         = $value['company'];
                                        $values['projectTitle'] = $value['projectTitle'];
                                        $values['product_id']   = $value['projectId'];
                                        $values['agency']       = $value['agency'];
                                        $productList[]          = $values;
                                    }
                                    
                                }
                            }
                            
                        }
                    }
                    
                }
            }
            $op = array_merge($productList, $companyLists);
            if ($envelopes_id != 0 && empty($op)) {
                $op = $capital->ganttChart($orderId, $envelopes_id);
            }
            $list     = $detailedWorkProcess->duration($op, $data['type'], $subordinate);
            $systemTag     = isset($data['systemTag']) ? $data['systemTag'] : 0;
            $tageList = $common->gantt($list, $data['type'], $orderId, $envelopes_id,$systemTag);
            r_date(['list' => $tageList['list'], 'date' => $tageList['date'], 'ganttDay' => $tageList['ganttDay'], 'weekday' => $tageList['weekday'],'agencyStartsDay'=>0]);
        } else {
            $envelopes_gantt_chart = db('envelopes_gantt_chart')->where('order_id', $orderId)->where('envelopes_id', $envelopes_id)->where('type', 3)->where('delete_time', 0)->find();
            r_date(json_decode($envelopes_gantt_chart['result'], true), 200);
        }
    }
    
    public function additionalSelection() {
        $data                = Authority::param(['orderId']);
        $order_setting       = \db('order_setting')->where('order_id', $data['orderId'])->find();
        $order_payment_nodes = \db('order_payment_nodes', config('database.zong'))->where('order_id', $data['orderId'])->where('payment_id', 0)->where('node_code', 2)->find();
        $list                = 0;
        if ($order_setting['payment_type'] != 2 && !empty($order_payment_nodes)) {
            $list = 1;
        }
        r_date($list, 200);
    }
    
    /*
     * 错漏项提示
     */
    public function errorAndOmissionPrompt(Detailed $detailed) {
        $data        = Request::instance()->post();
        $companyJson = empty($data['company']) ? [] : json_decode($data['company'], true);//清单
//        $productJson  = empty($data['productJson']) ? [] : json_decode($data['productJson'], true);//套餐
        $productJson  = [];//套餐
        $sys_config   = Db::connect(config('database.zong'))->table('sys_config')->where('keyss', 'strong_associations')->value('valuess');
        $sys_config   = json_decode($sys_config, true);
        $productList  = [];
        $companyLists = [];
        if ($companyJson) {
            if (!empty($companyJson)) {
                foreach ($companyJson as $ke => $value) {
                    $value['isProductChoose'] = true;
                    $companyLists[]           = $value;
                }
                
            }
        }
        if (!empty($productJson)) {
            foreach ($productJson as $item) {
                if (!empty($item['list'])) {
                    foreach ($item['list'] as $k => $v) {
                        if (!empty($v['data'])) {
                            foreach ($v['data'] as $ke => $value) {
                                $value['product_id']   = $value['projectId'];
                                $value['categoryName'] = $item['title'];
                                $productList[]         = $value;
                            }
                        }
                        
                    }
                }
                
            }
        }
        $op        = array_merge($companyLists, $productList);
        $setOf     = [];
        $exist     = [];
        $specsList = [];
        foreach ($sys_config as $k => $value) {
            foreach ($value['select'] as $k1 => $l) {
                $sys_config[$k]['select'][$k1]['type'] = $value['type'];
            }
            
            
        }
        $product_id = [];
        foreach ($op as $p) {
            if ($p['isProductChoose']) {
                $product_id[] = $p['product_id'];
            }
            $exist[] = ['product_id' => $p['product_id'], 'projectTitle' => $p['projectTitle'], 'categoryName' => $p['categoryName'], 'fang' => $p['fang']];
            foreach ($p['specsList'] as $m) {
                $specsList[] = ['option_value_id' => $m['option_value_id'], 'option_value_title' => $m['option_value_title'],];
            }
        }
        foreach ($op as $item) {
            foreach ($sys_config as $value) {
                if ($item['product_id'] == $value['id']) {
                    foreach ($value['select'] as $t) {
                        if ($value['type'] == 1) {
                            if (!in_array($t['id'], $product_id)) {
                                $setOf[] = ['id' => $t['id'], 'type' => $t['type']];
                            }
                            
                        }
                        if ($value['type'] == 2) {
                            if (($value['space'] == '' || (in_array($item['categoryName'], explode(",", $value['space'])) && (isset($value['release']) && $value['release'] <= $item['fang']))) && !in_array($t['id'], $product_id)) {
                                $setOf[] = ['id' => $t['id'], 'type' => $t['type']];
                            }
                            
                        }
                        if ($item['product_id'] == $value['id'] && $value['type'] == 3) {
                            foreach ($specsList as $lk) {
                                foreach ($value['select'] as $l) {
                                    if ($lk['option_value_id'] == $l['id'] && !in_array($value['ids'], array_column($exist, 'product_id'))) {
                                        $setOf[] = ['id' => $value['ids'], 'type' => 2];
                                    }
                                }
                            }
                            
                        }
                        if ($item['product_id'] == $value['id'] && $value['type'] == 4) {
                            foreach ($specsList as $lk) {
                                foreach ($value['select'] as $l) {
                                    if ($lk['option_value_id'] == $l['id'] && in_array($value['selectsid'], array_column($specsList, 'option_value_id'))) {
                                        $setOf[] = ['id' => $value['ids'], 'type' => 3, 'selectsid' => $value['selectsid']];
                                    }
                                }
                            }
                            
                        }
                    }
                }
            }
        }
        $required = [];
        foreach ($setOf as $i => $o) {
            if ($o['type'] == 1) {
                $required[] = $o;
            }
        }
        $detailed_id   = array_column($setOf, 'id');
        $detailedLists = $detailed->whereIn('detailed_id', $detailed_id)->where('is_compose', 1)->where('display', 1)->whereNull('deleted_at')->field('detailed_id,detailed_title,detailed_category_id,artificial,agency,warranty_years as warrantYears,warranty_text_1 as warrantyText1,warranty_text_2 as exoneration,groupss')->select();
        foreach ($detailedLists as $k => $value) {
            foreach ($setOf as $item) {
                
                if ($item['id'] == $value['detailed_id']) {
                    $value['association'] = $item['type'];
                    if (in_array($item['id'], array_column($required, 'id'))) {
                        $value['association'] = 1;
                    }
                }
                
            }
            $detailedLists[$k]['specifications'] = 0;
            if ($item['type'] == 3) {
                $detailedLists[$k]['detailed_title'] = $detailedLists[$k]['detailed_title'] . "(" . \db('detailed_option_value')->where('option_value_id', $item['selectsid'])->value('option_value_title') . ")";
                $detailedLists[$k]['specifications'] = $item['selectsid'];
            }
            $value['title']      = "全屋";
            $value['isWarranty'] = 1;
            if (!empty($value['warrantYears']) && $value['warrantYears'] != '0.00') {
                $value['warranty'] = ['warrantYears' => $value['warrantYears'], 'warrantyText1' => $value['warrantyText1'], 'exoneration' => $value['exoneration'],];
            } else {
                $value['warranty']   = null;
                $value['isWarranty'] = 0;
            }
            
            $value['types']    = 4;
            $value['group']    = $value['groupss'];
            $detailedListValue = $value->detailedListValue;
            if (!empty(array_column($detailedListValue, 'option_value_title'))) {
                $value['detailedListValues'] = $value['detailed_title'] . ',' . implode(array_column($detailedListValue, 'option_value_title'), ',');
                
            } else {
                $value['detailedListValues'] = $value['detailed_title'];
            }
            unset($value->detailedListValue, $value['warrantYears'], $value['warrantyText1'], $value['exoneration'], $value['groupss']);
            unset($detailedLists[$k]['sort'], $detailedLists[$k]['is_enable'], $detailedLists[$k]['created_at'], $detailedLists[$k]['updated_at'], $detailedLists[$k]['type'], $detailedLists[$k]['is_agency'], $detailedLists[$k]['condition']);
        }
        
        r_date($detailedLists, 200);
    }
    
    /*
     * 预计利润
     */
    public function estimatedProfit($capitalList, $give_money, $expense, $purchasing_discount, $purchasing_expense) {
        foreach ($capitalList as $k => $item) {
            $capitalList[$k]['give_money']          = $give_money;
            $capitalList[$k]['expense']             = $expense;
            $capitalList[$k]['purchasing_discount'] = $purchasing_discount;
            $capitalList[$k]['purchasing_expense']  = $purchasing_expense;
            $capitalList[$k]['created_time']        = time();
            $capitalList[$k]['main_price']          = 0;
            $capitalList[$k]['agent_price']         = 0;
            $option_value_id                        = 0;
            if (isset($item['specsList']) && !empty($item['specsList'])) {
                $option_value_id = array_column($item['specsList'], 'option_value_id');
            }
            $specsList                  = \db('detailed_option_value_material')->field("group_concat(detailed_option_value_material.invcode) as invcode,
                  CONCAT('[', GROUP_CONCAT(JSON_OBJECT('invcode',detailed_option_value_material.invcode,'option_value_id',detailed_option_value_material.option_value_id,'recommended_quantity',detailed_option_value_material.recommended_quantity,'sum',0) SEPARATOR ','), ']') as  content")->whereIn('detailed_option_value_material.option_value_id', $option_value_id)->find();
            $capitalList[$k]['invcode'] = empty($specsList) ? '' : $specsList['invcode'];//三
            $capitalList[$k]['content'] = empty($specsList) ? '' : $specsList['content'];//三
            if (($item['products'] != 1 || ($item['products'] == 1 && $item['unique_status'] == 1) || ($item['products'] == 1 && $item['unique_status'] == 0 && $item['is_product_choose'] == 1)) && $item['agency'] == 1) {
                $capitalList[$k]['agent_price']     = $item['toPrice'];
                $capitalList[$k]['daiMaterialCost'] = round($item['base_cost'] * $item['fang'], 2);
                $capitalList[$k]['daiLaborCost']    = $item['labor_cost_price'];
            }
            if (($item['products'] != 1 || ($item['products'] == 1 && $item['unique_status'] == 1) || ($item['products'] == 1 && $item['unique_status'] == 0 && $item['is_product_choose'] == 1)) && $item['agency'] == 0) {
                $capitalList[$k]['main_price']   = $item['toPrice'];
                $capitalList[$k]['zhuLaborCost'] = (string)round($item['sumMast'] * $item['fang'], 2);//三
            }
            
            $capitalList[$k]['order_fee'] = 0;
        }
        $this->us['city']  = config('cityId');
        $user              = $this->us;
        $u8c_invprice      = db('u8c_virtual_material', config('database.zong'))->where(function ($query) use ($user) {
            $query->where('store_id', $user['store_id'])->whereOr(function ($query) use ($user) {
                $query->where('city_id', $user['city'])->where('store_id', 0);
            });
        })->select();
        $labor_cost_config = db('labor_cost_config', config('database.zong'))->where('city_id', config('cityId'))->find();
        $interes_rate      = Db::connect(config('database.zong'))->table('sys_config')->where('keyss', 'interes_rate')->value('valuess');
        $interes_rate      = json_decode($interes_rate, true);
        $l                 = $capitalList;
        $result            = [];
        foreach ($l as $k => $v) {
            $zhuMaterialCost = 0;
            $zhuProfitMargin = 0;
            if (!empty($v['content'])) {
                $content = json_decode($v['content'], true);
                foreach ($content as $item) {
                    foreach ($u8c_invprice as $value) {
                        if ($item['invcode'] == $value['invcode'] && $item['sum'] == 0 && $value['profit_margin'] == '0.00') {
                            $content[$k]['sum'] = bcmul(bcmul($item['recommended_quantity'], $value['nabprice'], 2), $v['fang'], 2);
                            $zhuMaterialCost    += $content[$k]['sum'];
                            
                        }
                        if ($item['invcode'] == $value['invcode'] && $value['profit_margin'] > 0) {
                            $zhuProfitMargin += bcmul($v['main_price'], ($value['profit_margin'] / 100), 4);
                        }
                    }
                    
                }
                $v['content'] = json_encode($content);
            }
            
            $v['zhuMaterialCost'] = $zhuMaterialCost + $zhuProfitMargin;
            $v['zhuProfitMargin'] = $zhuProfitMargin;
            $v['daiOrderFee']     = 0;
            $v['zhuOrderFee']     = 0;
            if ($v['main_price'] == 0 && $v['agent_price'] != 0) {
                $v['daiOrderFee'] = $v['order_fee'];
                $v['zhuOrderFee'] = 0;
            }
            $result[$v['envelopes_id']][] = $v;
        }
        $zhuSum        = 0;
        $daiSum        = 0;
        $zhuLaborCosts = 0;
        $title         = '';
        if ($result) {
            foreach ($result as $k => $list) {
                $zhu           = array_sum(array_column($list, 'main_price')) - $result[$k][0]['give_money'] + $result[$k][0]['expense'];//祝主合同清单
                $zhuLaborCosts = array_sum(array_column($list, 'zhuLaborCost'));
                $zhuLaborCost  = $zhuLaborCosts + $zhu * ($labor_cost_config['fixed_labor_cost_ratio'] / 100);//人工费
                $zhuMeasurefee = bcmul($zhu, ($labor_cost_config['main_contract_measure_ratio'] / 100), 2);//措施费
                
                $zhuMaterialCost = array_sum(array_column($list, 'zhuMaterialCost'));//材料费
                $zhuOrderFee     = $result[$k][0]['order_fee'];//订单费
                $zhuProfit       = 0;
                $zhuProfit1      = 0;
                if ($zhu != 0) {
                    $zhuProfit1 = bcsub(bcsub(bcsub(bcsub($zhu, $zhuLaborCosts, 4), $zhuMeasurefee, 4), $zhuMaterialCost, 4), $zhuOrderFee, 4);
                    $zhuProfit  = bcsub(bcmul(sprintf('%.4f', $zhuProfit1 / $zhu), 100, 4), $labor_cost_config['fixed_labor_cost_ratio'], 4);
                    
                }
                $dai             = array_sum(array_column($list, 'agent_price')) - $result[$k][0]['purchasing_discount'] + $result[$k][0]['purchasing_expense'];
                $daiMeasurefee   = bcmul($dai, ($labor_cost_config['agency_contract_measure_ratio'] / 100), 2);
                $daiLaborCost    = array_sum(array_column($list, 'daiLaborCost'));
                $daiOrderFee     = $result[$k][0]['order_fee'];
                $daiMaterialCost = array_sum(array_column($list, 'daiMaterialCost'));//材料费
                
                if ($zhu != 0) {
                    $daiOrderFee = 0;
                }
                $daiProfit  = 0;
                $daiProfit1 = 0;
                
                if ($dai != 0) {
                    $estimate = $daiLaborCost + $daiMaterialCost;
                    if ($estimate == 0) {
                        $notes           = '因主材成本未配置，当前计算代购合同利润为系统推算';
                        $daiMaterialCost = array_sum(array_column($list, 'agent_price')) * 0.6;
                        $daiMeasurefee   = 0;
                    }
                    
                    $daiProfit1 = bcsub(bcsub(bcsub(bcsub($dai, $daiLaborCost, 4), $daiMeasurefee, 4), $daiMaterialCost, 4), $daiOrderFee, 4);
                    $daiProfit  = bcmul(sprintf('%.4f', $daiProfit1 / $dai), 100, 4);//利润
                    
                }
                $schemeTag['zhu']                  = (string)$zhuProfit1;//利润
                $schemeTag['zhuSum']               = (string)$zhu;//利润
                $schemeTag['zhuProfit']            = $zhuProfit;//利润
                $schemeTag['zhuLaborCosts']        = (string)$zhuLaborCosts;
                $schemeTag['zhuMeasurefee']        = (string)$zhuMeasurefee;
                $schemeTag['zhuMaterialCost']      = (string)$zhuMaterialCost;
                $schemeTag['zhuMaterialCostRatio'] = $labor_cost_config['main_contract_measure_ratio'] . '%';
                $schemeTag['zhuLixedlCostRatio']   = $labor_cost_config['fixed_labor_cost_ratio'] . '%';
                
                
                $schemeTag['dai']                  = $daiProfit1;//利润
                $schemeTag['daiSum']               = $dai;//利润
                $schemeTag['daiProfit']            = $daiProfit;
                $schemeTag['daiLaborCosts']        = (string)$daiLaborCost;//利润
                $schemeTag['daiMeasurefee']        = (string)$daiMeasurefee;//利润
                $schemeTag['daiMaterialCost']      = (string)$daiMaterialCost;//利润
                $schemeTag['daiMaterialCostRatio'] = $labor_cost_config['agency_contract_measure_ratio'] . '%';
                $schemeTag['zong']                 = $daiProfit + $zhuProfit;
                $schemeTag['zongProfit']           = bcmul(sprintf('%.4f', ($daiProfit1 + $zhuProfit1) / ($zhu + $dai)), 100, 4);//利润;
                $tageList[]                        = $schemeTag;
                
            }
        }
        $yuJiZhu   = 0;
        $yuJiDai   = 0;
        $yuJiDzong = 0;
        foreach ($interes_rate as $o) {
            if ($o['city_id'] == config('cityId')) {
                $yuJiZhu   = $o['zhu'] * 100;
                $yuJiDai   = $o['dai'] * 100;
                $yuJiDzong = $o['comprehensive'] * 100;
            }
        }
        if (isset($tageList)) {
//            if ($tageList[0]['zongProfit'] < $yuJiDzong) {
//                if (($yuJiDai > $tageList[0]['daiProfit']) && $tageList[0]['daiSum'] > 0) {
//                    return ['code' => 302, 'msg' => '当前利润不达标，请调整后重新提交:代购合同利润基线:' . $yuJiDai . '%(当前利润率:' . $tageList[0]['daiProfit'] . '%)；代购合同利润率：代购合同金额)' . $tageList[0]['daiSum'] . '-材料费' . $tageList[0]['daiMaterialCost'] . '-人工费' . $tageList[0]['daiLaborCosts'] . '-措施费' . $tageList[0]['daiMeasurefee'] . ')/代购合同金额' . $tageList[0]['daiSum'], 'type' => 2, 'order_rate' => $tageList[0]['daiProfit'], 'exceeding_rate' => $yuJiDai - $tageList[0]['daiProfit'], 'tageList' => $tageList, 'give_money' => $purchasing_discount, 'expense' => $purchasing_expense, 'labor_cost_config' => $labor_cost_config];
//                }
            if (($yuJiZhu > $tageList[0]['zhuProfit']) && $tageList[0]['zhuSum'] > 0) {
                return ['code' => 302, 'msg' => '当前利润不达标，请调整后重新提交:主合同利润基线:' . $yuJiZhu . '%(当前利润率:' . $tageList[0]['zhuProfit'] . '%)；主合同利润率：(主合同金额' . $tageList[0]['zhuSum'] . '-材料费' . $tageList[0]['zhuMaterialCost'] . '-人工费' . $tageList[0]['zhuLaborCosts'] . '-措施费' . $tageList[0]['zhuMeasurefee'] . ')/主合同金额' . $tageList[0]['zhuSum'] . ')-固定人工费比例' . $tageList[0]['zhuLixedlCostRatio'] . '', 'type' => 1, 'order_rate' => $tageList[0]['zhuProfit'], 'exceeding_rate' => $yuJiZhu - $tageList[0]['zhuProfit'], 'tageList' => $tageList, 'give_money' => $give_money, 'expense' => $expense, 'labor_cost_config' => $labor_cost_config];
//                }
//                return ['code' => 302, 'msg' => '当前利润不达标，请调整后重新提交综合利润基线:' . $yuJiDzong . '%(当前利润率:' . $tageList[0]['zongProfit'] . '%)'];
            }
            
        }
        return ['code' => 200, 'msg' => ''];
    }
    /**
     * 使用系统时间  重新提交
     */
    
    public function findBaseGanttDay(Capital $capital, DetailedWorkProcess $detailedWorkProcess, Common $common) {
        $data                  = Authority::param(['orderId', 'envelopesId']);
        $approval_record       = db('approval_record', config('database.zong'))->where(['relation_id' => $data['envelopesId'], 'city_id' => config('cityId'), 'order_id' => $data['orderId'], 'type' => 10, 'status' => 0])->column('id');
        $envelopes_gantt_chart = db('envelopes_gantt_chart')->where(['envelopes_id' => $data['envelopesId'], 'order_id' => $data['orderId'], 'delete_time' => 0])->find();
        $duration              = $envelopes_gantt_chart['duration'];
        if ($envelopes_gantt_chart['type'] == 3 || $envelopes_gantt_chart['type'] == 1) {
            $op         = $capital->ganttChart($data['orderId'], $data['envelopesId']);
            $list       = $detailedWorkProcess->duration($op, 2);
            $returnData = $common->gantt($list, 2, $data['orderId'], $data['envelopesId'],0);
            $duration   = $returnData['weekday'];
            db('envelopes_gantt_chart')->where(['envelopes_id' => $data['envelopesId'], 'order_id' => $data['orderId'], 'delete_time' => 0])->update(['delete_time' => time()]);
            db('envelopes_gantt_chart')->insert(['envelopes_id' => $data['envelopesId'], 'order_id' => $data['orderId'], 'result' => json_encode($returnData), 'type' => 2, 'duration' => $duration, 'created_time' => time()]);
        }
        
        if (!empty($approval_record)) {
            db('approval', config('database.zong'))->where('type', 13)->where('city_id', config('cityId'))->where('order_id', $data['orderId'])->whereIn('relation_id', $approval_record)->update(['status' => 1]);
            db('approval_schedule', config('database.zong'))->whereIn('relation_id', $approval_record)->update(['approval_status' => 2, 'remarks' => '申请人撤销审批']);
            db('approval_bef', config('database.zong'))->where('type', 13)->where('city_id', config('cityId'))->whereIn('approval_id', $approval_record)->where('state', 0)->update(['state' => 1]);
            db('approval_info', config('database.zong'))->where('type', 13)->where('city_id', config('cityId'))->whereIn('relation_id', $approval_record)->update(['approval_status' => 2, 'reject_desc' => '申请人撤销审批']);
            db('approval_record', config('database.zong'))->whereIn('id', $approval_record)->update(['status' => 2, 'explains' => '申请人撤销审批']);
        }
        db('envelopes')->where(['envelopes_id' => $data['envelopesId'], 'ordesr_id' => $data['orderId']])->update(['gong' => $duration]);
        r_date($duration, 200);
        
    }
    
    /*
       *施工中查看甘特图
       */
    public function ganttChart() {
        $data    = input('post.orderId');
        $orderId = $data;
        if (empty($orderId)) {
            jso_data(null, 300, '缺少参数');
        }
        $envelopes_id = db('envelopes')->where('ordesr_id', $orderId)->where('type', 1)->value('envelopes_id');;
        $envelopes_gantt_chart = db('envelopes_gantt_chart')->where('order_id', $orderId)->where('envelopes_id', $envelopes_id)->order('id desc')->where('delete_time', 0)->find();
        r_date(json_decode($envelopes_gantt_chart['result'], true), 200);
    }
    
    /*
     * 自定义主材新增
     */
    public function addCustomMainMaterials() {
        $data                      = Authority::param(['detailedCategoryId', 'unId', 'detailedTitle', 'warrantyYears', 'warrantyText', 'warrantyText2', 'optionValueTitle', 'fangLiang', 'totalPrice','isSave','isGive']);
        $param                     = Request::instance()->post();
        $created_at                = time();
        $detailed_category_2_id    = db('detailed_category')->where('detailed_category.pid', $data['detailedCategoryId'])->where('title','零采')->value('id');
        if(empty( $detailed_category_2_id)){
            $detailed_category_2_id    = db('detailed_category')->insertGetId(['pid'=>$data['detailedCategoryId'],'title'=>"零采",'is_agency'=>1,'created_at'=>time(),'is_enable'=>1]);
        }
        if($data['fangLiang']==0){
            r_date('', 300,'方量不能为0');
        }
        $artificial                = round($data['totalPrice'] / $data['fangLiang'], 2);
        if($data['isGive']==0){
            $data['warrantyYears']='';
            $data['warrantyText']='';
            $data['warrantyText2']='';
        }
        $list                      = ['un_id' => $data['unId'], 'detailed_category_id' => $data['detailedCategoryId'], 'detailed_category_2_id' => $detailed_category_2_id, 'detailed_title' => $data['detailedTitle'], 'artificial' => $artificial, 'agency' => 1, 'display' => $data['isSave'], 'is_compose' => 1, 'to_city' => config('cityId'), 'delivery_period_days_1' => 1, 'delivery_period_days_2' => 1, 'give' => 2, 'warranty_years' => $data['warrantyYears'], 'warranty_text_1' => $data['warrantyText'], 'warranty_text_2' => $data['warrantyText2'], 'is_fixed_cost' => 1, 'created_at' => $created_at, 'detail' => '', 'exp_text' => '', 'quotation_exp_text' => '', 'user_id' => $this->us['user_id'], 'number' => $data['fangLiang'], 'total_price' => $data['totalPrice']];
        $detailed_option_valueList = ['option_id' => 28, 'option_value_title' => $data['optionValueTitle'], 'price' => 0, 'artificial' => 0, 'work_time' => 0, 'is_enable' => 1, 'craft' => '', 'material' => '', 'created_at' => $created_at];
        $detailedUserId=0;
//        $detailedTitleArray=db('detailed')->where('agency',1)->where('user_id', $this->us['user_id'])->column('detailed_title');
//        if (isset($param['detailedId']) && $param['detailedId'] != 0 ){
//            $detailedInfo=db('detailed')->where('detailed_id', $param['detailedId'])->field('user_id,detailed_title')->find();
//            $detailedUserId=$detailedInfo['user_id'];
//            $detailedTitle=$detailedInfo['detailed_title'];
//        }
//        if(in_array($data['detailedTitle'],$detailedTitleArray)){
//            r_date('', 300,'报价中已有相同的自定义清单名称，需要修改成不一样的名称，最简单的方法就是加个空间名称或数字123即可。请修改后重新提交');
//        }
        if (isset($param['detailedId']) && $param['detailedId'] != 0 ) {
//            db('detailed')->where('detailed_id', $param['detailedId'])->update($list);
//            db('detailed_option_value')->where('detailed_id', $param['detailedId'])->update($detailed_option_valueList);
            $detailedId=$param['detailedId'];
            r_date($detailedId, 200);
        } else {
            $detailed            = db('detailed', config('database.zong'))->insertGetId($list);
            $detailed_option_valueList['detailed_id']     = $detailed;
            $detailed_option_value                        = db('detailed_option_value', config('database.zong'))->insertGetId($detailed_option_valueList);
            $detailedId=$detailed+1;
            $detailed_option_valueId=$detailed_option_value+1;
            $sql = "ALTER TABLE `detailed` AUTO_INCREMENT=".$detailedId;
            $sql1 = "ALTER TABLE `detailed_option_value` AUTO_INCREMENT=".$detailed_option_valueId;
            if(config('cityId')==241){
                Db::connect(config('database.bj'))->table('detailed')->query($sql);
                Db::connect(config('database.cq'))->table('detailed')->query($sql);
                Db::connect(config('database.dg'))->table('detailed')->query($sql);
                Db::connect(config('database.fs'))->table('detailed')->query($sql);
                Db::connect(config('database.wh'))->table('detailed')->query($sql);
                Db::connect(config('database.gz'))->table('detailed')->query($sql);
                Db::connect(config('database.sh'))->table('detailed')->query($sql);
                Db::connect(config('database.sz'))->table('detailed')->query($sql);
                Db::connect(config('database.gy'))->table('detailed')->query($sql);
                
                Db::connect(config('database.bj'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.cq'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.dg'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.fs'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.wh'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.gz'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.sh'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.sz'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.gy'))->table('detailed_option_value')->query($sql1);
                
            }elseif (config('cityId')==239){
                Db::connect(config('database.bj'))->table('detailed')->query($sql);
                Db::connect(config('database.cd'))->table('detailed')->query($sql);
                Db::connect(config('database.dg'))->table('detailed')->query($sql);
                Db::connect(config('database.fs'))->table('detailed')->query($sql);
                Db::connect(config('database.wh'))->table('detailed')->query($sql);
                Db::connect(config('database.gz'))->table('detailed')->query($sql);
                Db::connect(config('database.sh'))->table('detailed')->query($sql);
                Db::connect(config('database.sz'))->table('detailed')->query($sql);
                Db::connect(config('database.gy'))->table('detailed')->query($sql);
                
                Db::connect(config('database.bj'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.cd'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.dg'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.fs'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.wh'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.gz'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.sh'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.sz'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.gy'))->table('detailed_option_value')->query($sql1);
            }elseif (config('cityId')==172){
                Db::connect(config('database.bj'))->table('detailed')->query($sql);
                Db::connect(config('database.cd'))->table('detailed')->query($sql);
                Db::connect(config('database.dg'))->table('detailed')->query($sql);
                Db::connect(config('database.fs'))->table('detailed')->query($sql);
                Db::connect(config('database.cq'))->table('detailed')->query($sql);
                Db::connect(config('database.gz'))->table('detailed')->query($sql);
                Db::connect(config('database.sh'))->table('detailed')->query($sql);
                Db::connect(config('database.sz'))->table('detailed')->query($sql);
                Db::connect(config('database.gy'))->table('detailed')->query($sql);
                
                Db::connect(config('database.bj'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.cd'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.dg'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.fs'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.cq'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.gz'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.sh'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.sz'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.gy'))->table('detailed_option_value')->query($sql1);
                
            }elseif (config('cityId')==262){
                Db::connect(config('database.bj'))->table('detailed')->query($sql);
                Db::connect(config('database.cd'))->table('detailed')->query($sql);
                Db::connect(config('database.dg'))->table('detailed')->query($sql);
                Db::connect(config('database.fs'))->table('detailed')->query($sql);
                Db::connect(config('database.cq'))->table('detailed')->query($sql);
                Db::connect(config('database.gz'))->table('detailed')->query($sql);
                Db::connect(config('database.sh'))->table('detailed')->query($sql);
                Db::connect(config('database.sz'))->table('detailed')->query($sql);
                Db::connect(config('database.wh'))->table('detailed')->query($sql);
                
                Db::connect(config('database.bj'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.cd'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.dg'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.fs'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.cq'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.gz'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.sh'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.sz'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.wh'))->table('detailed_option_value')->query($sql1);
            }elseif (config('cityId')==375){
                Db::connect(config('database.bj'))->table('detailed')->query($sql);
                Db::connect(config('database.cd'))->table('detailed')->query($sql);
                Db::connect(config('database.dg'))->table('detailed')->query($sql);
                Db::connect(config('database.fs'))->table('detailed')->query($sql);
                Db::connect(config('database.cq'))->table('detailed')->query($sql);
                Db::connect(config('database.gz'))->table('detailed')->query($sql);
                Db::connect(config('database.gy'))->table('detailed')->query($sql);
                Db::connect(config('database.sz'))->table('detailed')->query($sql);
                Db::connect(config('database.wh'))->table('detailed')->query($sql);
                
                Db::connect(config('database.bj'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.cd'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.dg'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.fs'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.cq'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.gz'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.gy'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.sz'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.wh'))->table('detailed_option_value')->query($sql1);
            }elseif (config('cityId')==202){
                Db::connect(config('database.bj'))->table('detailed')->query($sql);
                Db::connect(config('database.cd'))->table('detailed')->query($sql);
                Db::connect(config('database.dg'))->table('detailed')->query($sql);
                Db::connect(config('database.fs'))->table('detailed')->query($sql);
                Db::connect(config('database.cq'))->table('detailed')->query($sql);
                Db::connect(config('database.gz'))->table('detailed')->query($sql);
                Db::connect(config('database.sh'))->table('detailed')->query($sql);
                Db::connect(config('database.gy'))->table('detailed')->query($sql);
                Db::connect(config('database.wh'))->table('detailed')->query($sql);
                
                Db::connect(config('database.bj'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.cd'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.dg'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.fs'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.cq'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.gz'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.sh'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.gy'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.wh'))->table('detailed_option_value')->query($sql1);
            }elseif (config('cityId')==501){
                Db::connect(config('database.sz'))->table('detailed')->query($sql);
                Db::connect(config('database.cd'))->table('detailed')->query($sql);
                Db::connect(config('database.dg'))->table('detailed')->query($sql);
                Db::connect(config('database.fs'))->table('detailed')->query($sql);
                Db::connect(config('database.cq'))->table('detailed')->query($sql);
                Db::connect(config('database.gz'))->table('detailed')->query($sql);
                Db::connect(config('database.sh'))->table('detailed')->query($sql);
                Db::connect(config('database.gy'))->table('detailed')->query($sql);
                Db::connect(config('database.wh'))->table('detailed')->query($sql);
                
                Db::connect(config('database.sz'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.cd'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.dg'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.fs'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.cq'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.gz'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.sh'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.gy'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.wh'))->table('detailed_option_value')->query($sql1);
            }elseif (config('cityId')==200){
                Db::connect(config('database.sz'))->table('detailed')->query($sql);
                Db::connect(config('database.cd'))->table('detailed')->query($sql);
                Db::connect(config('database.dg'))->table('detailed')->query($sql);
                Db::connect(config('database.fs'))->table('detailed')->query($sql);
                Db::connect(config('database.cq'))->table('detailed')->query($sql);
                Db::connect(config('database.bj'))->table('detailed')->query($sql);
                Db::connect(config('database.sh'))->table('detailed')->query($sql);
                Db::connect(config('database.gy'))->table('detailed')->query($sql);
                Db::connect(config('database.wh'))->table('detailed')->query($sql);
                
                
                Db::connect(config('database.sz'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.cd'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.dg'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.fs'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.cq'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.bj'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.sh'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.gy'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.wh'))->table('detailed_option_value')->query($sql1);
            }elseif (config('cityId')==205){
                Db::connect(config('database.sz'))->table('detailed')->query($sql);
                Db::connect(config('database.cd'))->table('detailed')->query($sql);
                Db::connect(config('database.dg'))->table('detailed')->query($sql);
                Db::connect(config('database.gz'))->table('detailed')->query($sql);
                Db::connect(config('database.cq'))->table('detailed')->query($sql);
                Db::connect(config('database.bj'))->table('detailed')->query($sql);
                Db::connect(config('database.sh'))->table('detailed')->query($sql);
                Db::connect(config('database.gy'))->table('detailed')->query($sql);
                Db::connect(config('database.wh'))->table('detailed')->query($sql);
                
                Db::connect(config('database.sz'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.cd'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.dg'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.gz'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.cq'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.bj'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.sh'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.gy'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.wh'))->table('detailed_option_value')->query($sql1);
            }elseif(config('cityId')==216){
                Db::connect(config('database.sz'))->table('detailed')->query($sql);
                Db::connect(config('database.cd'))->table('detailed')->query($sql);
                Db::connect(config('database.fs'))->table('detailed')->query($sql);
                Db::connect(config('database.gz'))->table('detailed')->query($sql);
                Db::connect(config('database.cq'))->table('detailed')->query($sql);
                Db::connect(config('database.bj'))->table('detailed')->query($sql);
                Db::connect(config('database.sh'))->table('detailed')->query($sql);
                Db::connect(config('database.gy'))->table('detailed')->query($sql);
                Db::connect(config('database.wh'))->table('detailed')->query($sql);
                
                Db::connect(config('database.sz'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.cd'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.fs'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.gz'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.cq'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.bj'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.sh'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.gy'))->table('detailed_option_value')->query($sql1);
                Db::connect(config('database.wh'))->table('detailed_option_value')->query($sql1);
            }
           
            $list['detailed_id'] = $detailed;
            db('detailed')->insert($list);
            $detailed_option_valueList['option_value_id'] = $detailed_option_value;
            db('detailed_option_value')->insert($detailed_option_valueList);
            db('detailed_option_value', config('database.zong'))->where('option_value_id', $detailed_option_value)->update(['deleted_at'=>$created_at]);
            db('detailed', config('database.zong'))->where('detailed_id', $detailed)->update(['deleted_at'=>$created_at]);
            $detailedId=$detailed;
        }
        
        r_date($detailedId, 200);
        
    }
    
    /*
     * 清单分类
     */
    public function listClassification() {
        $data              = Authority::param(['id']);
        $detailed_category = db('detailed_category')->where('detailed_category.is_enable', 1)->where('detailed_category.is_agency', 1)->field('id,title')->where('sort','<',200)->where('detailed_category.pid', 0)->order('sort asc')->select();
        $unit              = db('unit')->field('title,id')->select();
        $detailed          = null;
        if ($data['id'] != 0) {
            $detailed                     = db('detailed')->where('detailed_id', $data['id'])->field('un_id as unId,detailed_category_id as detailedCategoryId,detailed_title as detailedTitle,artificial,warranty_years as warrantyYears,warranty_text_1 as warrantyText,warranty_text_2 as warrantyText2,total_price as totalPrice,number as fangLiang,display as isSave')->find();
            $detailed_option_value        = db('detailed_option_value')->where('detailed_id', $data['id'])->field('option_value_title as optionValueTitle')->find();
            $detailed['optionValueTitle'] = $detailed_option_value['optionValueTitle'];
            $detailed['isGive'] =0;
            if(!empty($detailed['warrantyYears']) && $detailed['warrantyYears'] !='0.00'){
                $detailed['isGive'] =1;
            }
            
        }
        foreach ($detailed_category as $k => $item) {
            $detailed_category[$k]['selected'] = 0;
            if (!empty($detailed['detailedCategoryId']) && $item['id'] == $detailed['detailedCategoryId']) {
                $detailed_category[$k]['selected'] = 1;
            }
        }
        foreach ($unit as $k => $item) {
            $unit[$k]['selected'] = 0;
            if (!empty($detailed['unId']) && $item['id'] == $detailed['unId']) {
                $unit[$k]['selected'] = 1;
            }
        }
        unset($detailed['unId'], $detailed['detailedCategoryId']);
        r_date(['list' => $detailed, 'detailedCategory' => $detailed_category, 'unit' => $unit], 200);
    }
    /*
     * 清单详情图片
     */
    public function detailedOptionValue(DetailedOption $detailedOption){
        $data                   = Authority::param(['id','optionValueId','optionValueIdList']);
        $optionValueIdList=explode(",",$data['optionValueIdList']);
        $getOptionValue = $detailedOption->with(['detailedListOptionValues' => function ($query) use ($data) {
            $query->where('detailed_option_value.detailed_id', $data['id'])->group('detailed_option_value.option_value_id');
        }])->where('condition', '<>', 2)->order('option_id desc')->select();
        $detailed_option_sort   = db('detailed_option_sort', config('database.zong'))->where('detailed_id', $data['id'])->select();
        $info=null;
        $getOptionList=null;
        foreach ($getOptionValue as $k => $value) {
            if ($detailed_option_sort) {
                foreach ($detailed_option_sort as $item) {
                    if ($item['option_id'] == $value['option_id']) {
                        $value['sort'] = $item['sort'];
                    }
                    
                }
                
            }
            $value['select']= 0;
            $value['option_value_id']= 0;
            unset($value['type'],$value['is_agency'],$value['sort'],$value['condition'],$value['type']);
            if (!empty($value['detailed_list_option_values'])) {
                $value['sort']           = isset($value['sort']) ? $value['sort'] : 0;
                $detailed_list_option_values=$value['detailed_list_option_values'];
                foreach ($detailed_list_option_values as $key=>$val){
                    $val['desc_tag']           = empty($val['desc_tag']) ?null : json_decode($val['desc_tag'],true);
                    $val['desc_text'] = empty($val['desc_text']) ?null : json_decode($val['desc_text'],true);
                    $val['desc_attachment']           = empty($val['desc_attachment']) ?null: json_decode($val['desc_attachment'],true);
                    if(empty($val['desc_attachment'])){
                        unset($detailed_list_option_values[$key]);
                    }
                    unset($val['type'],$val['price'],$val['condition'],$val['artificial'],$val['work_time'],$val['option_id'],$val['sales']);
                    if($val['option_value_id']==$data['optionValueId']){
                        $info['option_id']= $value['option_id'];
                        $info['optionTitle']=$value['option_name'].':'.$val['option_value_title'];
                        $info['desc_tag']= $val['desc_tag'];
                        $info['desc_text']=$val['desc_text'];
                        $info['desc_attachment']=$val['desc_attachment'];
                        $value['select']= 1;
                        $value['option_value_id']= $val['option_value_id'];
                    }
                    foreach ($optionValueIdList as $item){
                        if($item==$val['option_value_id']){
                            $value['option_value_id']= $val['option_value_id'];
                            $value['img']=$val['desc_attachment'][0];
                        }
                       
                    }
           
                }
                if($value['option_value_id'] !=0){
                   $value['detailed_list_option_valuess']=$detailed_list_option_values;
                   if(empty( $value['img'])){
                       unset($value);
                   }else{
                       unset($value['detailed_list_option_values']);
                       $getOptionList[] = $value;
                   }
                  
                }
               
               
            }
            
        }
        if(!empty($getOptionList)){
            $info['list']=array_merge($getOptionList);
        }
       
        r_date($info, 200);
    }
    /*
     * 清单详情同规格其他选项
     */
    public function sameDetailedOptionValue(DetailedOption $detailedOption){
        $data                   = Authority::param(['id','optionId','optionValueId']);
        $getOptionValue = $detailedOption->with(['detailedListOptionValues' => function ($query) use ($data) {
            $query->where('detailed_option_value.detailed_id', $data['id'])->group('detailed_option_value.option_value_id');
        }])->where('condition', '<>', 2)->where('option_id',$data['optionId'])->order('option_id desc')->select();
        $info=null;
        $getOptionList=null;
        foreach ($getOptionValue as $k => $value) {
        if (!empty($value['detailed_list_option_values'])) {
            $value['sort'] = isset($value['sort']) ? $value['sort'] : 0;
            $detailed_list_option_values=$value['detailed_list_option_values'];
            foreach ($detailed_list_option_values as $key => $val) {
                $val['desc_text'] = empty($val['desc_text']) ? null : json_decode($val['desc_text'], true);;
                $val['desc_attachment'] = empty($val['desc_attachment']) ? null : json_decode($val['desc_attachment'], true);
                $val['select']  = 0;
                if(empty($val['desc_attachment'])){
                   unset($detailed_list_option_values[$key]);
                }
                $val['img']=$val['desc_attachment'][0];
                unset($val['type'], $val['price'], $val['condition'], $val['artificial'], $val['work_time'], $val['option_id'], $val['sales']);
                if ($val['option_value_id'] == $data['optionValueId']) {
                    $info['id']        = $data['id'];
                    $info['option_id']        = $data['optionId'];
                    $info['optionTitle']=$value['option_name'].':'.$val['option_value_title'];
                    $info['optionName']=$value['option_name'];
                    $info['desc_attachment']=$val['desc_attachment'];
                    $info['desc_tag']        = $val['desc_tag'];
                    $val['select']  = 1;
                    $info['desc_text']       = $val['desc_text'];
                }
                
            }
            $getOptionList = $detailed_list_option_values;
        }
        }
        $info['list']=array_merge($getOptionList);
        r_date($info, 200);
    }
    /**
     * 获取订单属性根据order表
     */
    public function attribute()
    {
         $data         = Authority::param(['orderId']);
        $pro_id = db('order')->where('order_id', $data['orderId'])->value('business_type');
        $group   = 1;
        if ($pro_id == 2 || $pro_id == 3) {
            $group        = 2;
        }
        r_date($group, 200);
    }
}